Project development encountered a problem, the confused to achieve, and now focus on what this is a situation, the great gods if they see the hope to give some guidance.
Problem: The subclass has the same properties and methods as the parent class, instantiates the subclass to the parent class, invokes the Get, set method of the corresponding property, and prints out the information that shows the property value of the subclass, what is the reason?
The code is as follows--parent class:
Public class Freath { privateint1; Public int Geta () { return A; } Public void SetA (int a) { this. A = A; }}
Sub-Class A:
Public class A extends freath{ privateint2; Public int Geta () { return A; } Public void SetA (int a) { this. A = A; } }
Sub-Class B:
Public class B extends freath{ privateint3; Public int Geta () { return A; } Public void SetA (int a) { this. A = A; }}
Test class:
Public classTest { Public Static voidMain (string[] args) {Freath FA=NewA (); Freath FB=NewB (); System. out. println (Fa.geta () +""); System. out. println (((A) FA). Geta () +""); System. out. println (Fb.geta () +""); System. out. println (((B) FB). Geta () +""); } }
Output Result:
The first such result is really what I want, but for the inside of the logic, very puzzled, but also hope to get guidance.
For the above situation I made a few changes, the printed result is completely changed:
Parent class:
Public class Freath { privateint1; Public int Geta () { return A; } Public void SetA (int a) { this. A = A; }}
Sub-Class A:
public class A extends freath{ private int a = 2 // public int Geta () { // return A; // // public void SetA (int a) { // THIS.A = A; //
Sub-Class 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 classTest { Public Static voidMain (string[] args) {Freath FA=NewA (); Freath FB=NewB (); System. out. println (Fa.geta () +""); System. out. println (((A) FA). Geta () +""); System. out. println (Fb.geta () +""); System. out. println (((B) FB). Geta () +""); } }
Results:
In the case of these two cases, my understanding is that the first case belongs to: The parent class property is private, the subclass cannot inherit, the property method of the parent class is public, the subclass can inherit the override, the result is that the parent class is equivalent to a portal that provides the method of calling the subclass, and after the subclasses override these methods, When called, the property value of the child class is printed out. The second case is because the parent class's property is private, the subclass cannot inherit, the subclass inherits the method of the parent class, but does not rewrite it, so the information of the parent class is printed when it is called.
java--inheritance