When the parent class reference points to the subclass object member variable inheritance problem

package chapter_03.step_03;
/**
 * 当父类引用指向子类对象    成员变量继承问题
 * @author Administrator
 *
 */
public class Test02 {
public static void main(String[] args) {
Parent p = new Child();
Child c = new Child();
System.out.println("p.a = " + p.a);
System.out.println("p.getA() = " + p.getA());
System.out.println("c.a = " + c.a);
System.out.println("c.getA() = " + c.getA()); Parent p2 = new Child2(); System.out.println("p2.a = " + p2.a); System.out.println("p2.getA() = " + p2.getA()); /** p.a = 10 p.getA() = 10 c.a = 20 c.getA () = 10










p2.a = 30
p2.getA() = 30
*/
/**
* When the parent class reference points to the child class object
* When calling a method, call the parent class (if there is one, you cannot call the method unique to the child class, this is The disadvantage of the parent class reference pointing to the subclass object), run and see the subclass (actually run the subclass method)
* When calling to get the value of the member variable, the acquisition is super.a, and the value of the member variable of the parent class is naturally acquired. To change the class, you can override the value in the subclass constructor at initialization time
*/
}
}


class Parent{
int a = 10;
public int getA() {
return a;
}
}


class Child extends Parent{
int a = 20;
}


class Child2 extends Parent{
public Child2() {
this.a = 30;
}
/**
 * Automatically generate an overriding method, it can be seen that super.getA()->super.a is called
@Override
public int getA() {
return super.getA();
}
*/
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325857358&siteId=291194637