重写只发生在方法里面,不包括属性子类继承父类后,如存在同名、同参、同返回值的方法,子类方法会重写父类的同名方法,那么如果父子存在相同的属性名会重写吗?参见如下代码: public class Pet { public String name ;
public String getName() { return name; } public Pet(){ this.name = "pet"; } } public class Dog extends Pet { public String name; public Dog(){ this.name = "dog"; }
} public static void main(String[] args) { Pet pet = new Dog(); System.out.println(pet.name); System.out.println(pet.getName()); } 系统运行后,输出结果为两个"pet",而没有任何"dog",为什么? 原来多态仅针对实例方法,与实例的属性无关。 如果修改Dog类,增加getName方法后,输出结果如何? public class Dog extends Pet { public String name; public String getName() { return name; } public Dog(){ this.name = "dog"; } } 输出结果为"pet" 和"dog",这验证了上述的结论:重写只对方法有效,对属性无效!
public class Pet {
public String name ;
public String getName() {
return name;
}
public Pet(){
this.name = "pet";
}
}
public class Dog extends Pet {
public String name;
public Dog(){
this.name = "dog";
}
}
public static void main(String[] args) {
Pet pet = new Dog();
System.out.println(pet.name);
System.out.println(pet.getName());
}
系统运行后,输出结果为两个"pet",而没有任何"dog",为什么?
原来多态仅针对实例方法,与实例的属性无关。
如果修改Dog类,增加getName方法后,输出结果如何?
public class Dog extends Pet {
public String name;
public String getName() {
return name;
}
public Dog(){
this.name = "dog";
}
}
输出结果为"pet" 和"dog",这验证了上述的结论:重写只对方法有效,对属性无效!
子类中有了名称一样的属性,是隐藏了父类的属性,实际上用super.属性名,还是可以得到父类的非private属性.
public int x = 10;
public void p(){
System.out.println(super.x);
System.out.println(this.x);
}
public static void main(String[] args){
Son s = new Son();
s.p();
}
}结果
5
10所以没有你所说的,属性重写。其实是因为,子类对象内隐式封装了一个基类对象。