JAVA-inheritance, java inherits multiple classes
I encountered a problem in project development, and I was confused about how to implement it. Now I will focus on the situation. If you can see it, I hope to give some advice.
Problem: The subclass has the same attributes and methods as the parent class. The subclass is instantiated as the parent class, And the get and set methods of the corresponding properties are called. The printed information shows the property values of the subclass, what is the reason?
The Code is as follows -- parent class:
public class Freath { private int a = 1; public int getA() { return a; } public void setA(int a) { this.a = a; }}
Subclass:
public class A extends Freath{ private int a = 2; public int getA() { return a; } public void setA(int a) { this.a = a; } }
Subclass B:
public class B extends Freath{ private int a = 3; public int getA() { return a; } public void setA(int a) { this.a = a; }}
Test class:
public class Test { public static void main(String[] args) { Freath fa = new A(); Freath fb = new B(); System.out.println(fa.getA()+""); System.out.println(((A) fa).getA()+""); System.out.println(fb.getA()+""); System.out.println(((B) fb).getA()+""); } }
Output result:
First of all, this result is indeed what I want, but it is difficult to understand the logic in it. I hope I can get some advice.
I made another modification to the above situation, and the printed results changed completely:
Parent class:
public class Freath { private int a = 1; public int getA() { return a; } public void setA(int a) { this.a = a; }}
Subclass:
public class A extends Freath{ private int a = 2;// public int getA() {// return a;// }//// public void setA(int a) {// this.a = a;// }}
Subclass B:
public class B extends Freath{ private int a = 3;// public int getA() {// return a;// }//// public void setA(int a) {// this.a = a;// }}
Test class:
public class Test { public static void main(String[] args) { Freath fa = new A(); Freath fb = new B(); System.out.println(fa.getA()+""); System.out.println(((A) fa).getA()+""); System.out.println(fb.getA()+""); System.out.println(((B) fb).getA()+""); } }
Result:
In my understanding, the first case is that the attributes of the parent class are private, the subclass cannot be inherited, and the attributes and methods of the parent class are public, subclass can be inherited and overwritten. In the above case, the parent class is equivalent to an entry that provides the method for calling subclass. After the subclass overrides these methods, when it is called, the property value of the subclass is printed. In the second case, because the attributes of the parent class are private, the Child class cannot be inherited. The Child class inherits the method of the parent class but is not overwritten, the information of the parent class is printed.