标签:
class Base{
????int x = 1;
????static int y = 2;
????String name(){
????????return "mother";
????}
????static String staticname(){
????????return "static mother";
????}
}
class Subclass extends Base{
????int x = 4;
????int y = 5;
????String name(){
????????return "baby";
????}
????static String staticname(){
????????return "static baby";
????}
}
public class Test02{
????public static void main(String[] args){
????????Subclass s = new Subclass();
????????System.out.println(s.x+" "+s.y+" "+s.name()+" "+s.staticname());
????????Base s1 = s;
????????System.out.println(s1.x+" "+s1.y+" "+s1.name()+" "+s1.staticname());
????}
}
?
/*
结果:
?
4 5 baby static baby
1 2 baby static mother
结论:
?
父类的实例方法被子类的同名实例方法覆盖
父类的静态方法被子类的同名静态方法隐藏
父类的实例变量和类变量可以被子类的实例变量和类变量隐藏
?
就"Base s1 = s"来说:把s赋值给s1时,s(子类)的方法name已经把父类的name方法覆盖了,却没有覆盖static name,而是隐藏了它。
赋值给s1后,s1的name方法已经变成了"baby",而staticname方法只是被隐藏而没有被覆盖,现在有还原成了"static mother"
*/
标签:
原文地址:http://www.cnblogs.com/iucforever/p/4828603.html