在学习面向对象的三大特征——继承中,有一个问题困扰着我:
子类是否会继承父类的私有成员变量呢。
答案是肯定的,子类会继承父类的私有成员变量。
父类
public class Animal {
private int age;
public Animal() {
super();
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
子类
public class Dog extends Animal{
private int weight;
public Dog() {
super();
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}
再来一个测试类
public class MyTest {
public static void main(String[] args) {
Dog dog =new Dog();
dog.setAge(2);
System.out.println(dog.getAge());
}
}
dog这个对象调用自己继承自父类Animal的方法getAge()和setAge()这个是没有问题的。
如果子类不能继承父类的私有变量,那么;
在getAge()与setAge()方法中中的age变量在dog中是没有的,没有这个变量则编译会报错,运行也会出错。
但是在实际调用中,编译器没报错,运行也没错。
那么就说明,Dog肯定是继承了Animal的私有成员变量age,使得自己拥有age属性。