Before you make a mistake, the variable does not have a "rewrite" to say, only the method can be "rewritten". If we declare a variable in the subclass that is the same as the parent class, the actual case is that there are two variables of the same type and name in the memory heap of the child class.
Now consider a situation where, as shown below, we declare a name in the subclass like a variable in the parent class, but a variable of type I (an int, a double), and we have a print () printing I in the parent class, so when we call this print () from the object of the subclass, Which one is he going to print?
classSuperclass { Public inti; Superclass () {i=10; System.out.println ("Superclass () is construted."); } Public voidprint () {System.out.println ("The I in Superclass:" +i); }}classSubclassextendsSuperclass { Public Doublei; Subclass () {i=20.0; System.out.println ("Subclass () is constructed."); } Public voidprintsub () {System.out.println ("The I in Subclass:" +i); }} Public classTestdemo { Public Static voidMain (string[] args) {Subclass Sub=Newsubclass (); System.out.println ("SUB.I is:" +SUB.I); Sub.printsub (); Sub.print (); The result of the output is: Superclass () is construted. Subclass () is CONSTRUCTED.SUB.I:20.0The i in subclass:20.0The i in superclass:10
We know very well that if you re-declare the same print () function in a subclass, the print () function of the parent class will be overwritten, and print () outputs the double i=20.0 defined in the subclass, so I'm not going to discuss this situation.
From the output results, the sub-class subclass object sub access to the value of I is double i=20.0, but through the subclass object call in the parent class defined in print (), printing is still the parent class int i=10, how to explain this situation?
Now let's change the subclass:
classSubclassextendsSuperclass { Public inti; Subclass () {i=20; System.out.println ("Subclass () is constructed."); } Public voidprintsub () {System.out.println ("The I in Subclass:" +i); }}/*the test results are*/superclass () is construted. Subclass () is CONSTRUCTED.SUB.I:20The i in subclass:20The i in superclass:10
As we can see, even if we declare an identical I in subclass subclass, the subclass object calls the print () defined in the parent class, and still prints the int i=10 in the parent class.
Java subclass inherits problems from parent class members