Public classMaintest {Static classA { Public inti; Public voidf () {System.out.println ("AAAAA"); } } Static classBextendsA { Public voidf () {System.out.println ("BBBBB"); } Public voidg () {System.out.println ("GGGG"); } } Public Static voidMain (string[] args) {A A1=NewB ();//correct, the subclass object is assigned to the parent class reference//b B1 = (b) new A ();//error, Parent object cannot be directly assigned to subclass referenceA A2=NewB (); A2.I= 1;//correct, access the parent class PropertyA2.F ();//right, subclass method that accesses the subclass of the overridden parent class//a2.g ();//error, cannot access a method that is unique in subclassesA A3=NewA (); B B3=NewB ();//B3 = (B) A3;//error, the parent class reference refers to the parent class object and cannot be cast to a subclass reference. A A4=NewB (); B B4=NewB (); B4= (B) A4;//correct, at which point the parent class reference refers to the child class object. You can cast to a subclass reference, you must use a strong turn, }}
1) A subclass object can be assigned directly to a parent class reference, but the parent object cannot be directly assigned to a subclass reference. Because subclasses can be thought of as a special parent class, that is, one of the parent classes, but the parent class cannot be treated as a subclass under any circumstances. For example, a dog is a child of an animal.
Class, dogs can be regarded as an animal, but animals are not necessarily dogs.
A A1 = new B ();//Correct, the subclass object is assigned to the parent class reference
B B1 = new A ();//error, Parent object cannot be directly assigned to subclass reference
2) The reference type of the parent class reference to the child class object can access only some properties and methods of the parent class, and cannot access properties and methods that are unique to the child class.
A A2 = new B ();
a2.i = 1; Correct, access the parent class property
A2.F (); Right, subclass method that accesses the subclass of the overridden parent class
A2.G (); Error, cannot access a method that is unique in subclasses
3) You can cast a parent class reference to a subclass reference when the parent reference refers to a child class object.
A a3 = new A ();
b B3 = new B ();
B3 = (B) a3;//error, parent class refers to the parent class object and cannot be cast to a subclass reference.
A a4 = new B ();
b B4 = new B ();
B4 = (B) a4;//is correct, at which point the parent class refers to the subclass object. You can cast to a subclass reference, but you must use a cast
Most of the blog from the network, if there is a copyright issue please contact me to delete or modify, blog content mainly for their own study and note use and hope to provide some help to the needs of friends, do not like to spray, you are welcome to point out the mistakes, learning, progress.
Contact e-mail:[email protected]
qq:1129368407
Some problems needing attention in Java polymorphism