package test;
public class Base {
void method(){
System.out.println("method of Base");
}
static void staticMethod(){
System.out.println("static method of Base");
}
public static void main(String[] args) {
Base sub1=new Sub();
sub1.method();
sub1.staticMethod();
Sub sub2=new Sub();
sub2.method();
sub2.staticMethod();
}
}
class Sub extends Base{
void method(){
System.out.println("method of Sub");
}
static void staticMethod(){
System.out.println("static method of Sub");
}
public class Base {
void method(){
System.out.println("method of Base");
}
static void staticMethod(){
System.out.println("static method of Base");
}
public static void main(String[] args) {
Base sub1=new Sub();
sub1.method();
sub1.staticMethod();
Sub sub2=new Sub();
sub2.method();
sub2.staticMethod();
}
}
class Sub extends Base{
void method(){
System.out.println("method of Sub");
}
static void staticMethod(){
System.out.println("static method of Sub");
}
}
输出结果:
method of Sub
static method of Base
method of Sub
static method of Sub
变量sub1和sub2都引用了Sub类的实例,sub1.method()和sub2.method()都调用了Sub实例的method()方法,此时父类的Base的method()被子类覆盖。
当sub1执行staticMethod()时,调用的是Base类的方法,可见父类的静态方法不能被子类覆盖。