java 继承隐藏与覆盖:
1)子类只能覆盖父类非静态方法;且只能隐藏父类的同名变量和静态方法。
覆盖:调用的总是实例化对象的同名方法;
隐藏:调用的总是引用的类型的同名方法或同名变量;
2)代码实例:
public class A {
public int i=0;
public void hello(){
System.out.println("this is A");
}
public static void staticTtest(){
System.out.println("A's static");
}
}
public class B extends A{
public int i=1; //隐藏
public void hello(){
System.out.println("this is B"); //覆盖
}
public static void staticTtest(){ //隐藏
System.out.println("B's static");
}
}
public class appMain {
public static void main(String[] args){
A a=new B();
a.hello(); //非静态方法,故覆盖;输出B的hello方法
System.out.println(a.i); //同名变量,故隐藏;A引用类型,故输出A的i变量
a.staticTtest(); //同名静态方法,故隐藏;A引用类型,故输出A的staticTtest
B b=(B)a;
b.hello(); //非静态方法,故覆盖;输出B的hello方法
System.out.println(b.i); //同名变量,故隐藏;B引用类型,故输出B的i变量
b.staticTtest(); //同名静态方法,故隐藏;B引用类型,故输出B的staticTtest
}
}