Home > Back-end > JAVA polymorphism in the parent class reference subclass object
JAVA polymorphism in the parent class reference subclass object
Time:05-15
The parent class reference deposit is a subclass of address, should not draw on the subclass variables and methods? Why is to be obtained all variables and methods of the parent class (or subclass rewrite of the parent class method)
CodePudding user response:
Method the parent class A, attributes a1, a2, in a. this is ava, defined in Subclass inherits A, B attribute b1, method b2, inherited from A get a1, a2 Then you use A=new B (); This line of code that can be divided into two steps 1, A, A. Defines a reference to a, is a class a reference, so have only a a1 and a2, this time also there is no point to an object in memory 2, a=new B (); Will be a new object of class B (B) to reference a, this time has a default transformation upwards, but the b1 and b2 is defined in B.j ava, has nothing to do with a, B belongs to own, only B references can be used, a reference to the right to use, This is the code compile time is established, so the compiler cannot pass,