The object transformation of basic Java Learning

Source: Internet
Author: User

Object Transformation (Casting):

1) A reference type variable of a base class can point to an object of its child class

2) A reference to a base class does not have access to the newly added members (properties and methods) of its child class object

3) You can use the reference variable instanceof class name to determine whether the object to which the reference variable is pointing belongs to the class or subclass of that class

4) An object of a subclass can be used as an object of a base class to use called up Transformation (upcasting), which is called downward transformation (downcasting)

 Packagejavastudy.summary;/*** Parent Class Animal *@authorGaCl **/classAnimal { PublicString name;  PublicAnimal (String name) { This. Name =name; }}/*** Subclass Cat Inherits Animal *@authorGaCl **/classCatextendsAnimal {/*** Cat adds its own unique properties*/     PublicString Eyecolor;  PublicCat (string n, string c) {Super(n);//constructor method for calling parent class animal         This. Eyecolor =C; }}/*** Subclass Dog Inherits Animal *@authorGaCl **/classDogextendsAnimal {/*** The Dog class adds its own unique properties*/     PublicString Furcolor;  PublicDog (string n, string c) {Super(n);//constructor method for calling parent class animal         This. Furcolor =C; }}/*** Below are the test procedures for these three classes *@authorGaCl **/ Public classTestclasscast {/**     * @paramargs*/     Public Static voidMain (string[] args) {Animal a=NewAnimal ("name"); Cat C=NewCat ("CatName", "Blue"); Dog D=NewDog ("Dogname", "BLACK"); /*** A instanceof animal This sentence means a is an animal?         * A is a animal this class is an instance object, so a is of course an animal, and the result is true. */System.out.println (String.Format ("A instanceof animal result is%s", ainstanceofAnimal));//true        /*** C is a reference to the Cat class instance object, that is, C is the instance object, * So "C is an animal" the result of printing is true.         * d is also the same, so "D is an animal" print out the result is also true. */System.out.println (String.Format ("C instanceof Animal result is%s", CinstanceofAnimal));//trueSYSTEM.OUT.PRINTLN (The result of String.Format ("D instanceof Animal is%s", DinstanceofAnimal));//true        /*** Here it is said that "animal is a cat", not logical, so the printed result is false. */System.out.println (String.Format ("A instanceof The result of cat is%s", ainstanceofCat)); /*** This sentence is more interesting, a itself is a reference to an instance object of the animal class, * But now this reference does not point to the instance object of the animal class, but instead points to an instance object of the class of dog, * Here is the parent class object's citation         Uses an instance object that points to a subclass. */a=NewDog ("Bigyellow", "Yellow"); System.out.println (a.name);//Bigyellow        /*** The Furcolor property here is a newly added attribute of the subclass on the basis of inheriting the parent class, which is not the parent class. * Therefore, it is not permissible to use the reference object A of the parent class to access the newly added member variable inside the subclass object, * because in the compiler eye, you are a reference object of the Animal class object, you can only access the name attribute in the Animal class object, * except a         The properties inside the Nimal class can be accessed beyond the access of member variable A in other classes.         * Here the Furcolor property is a property inside the dog class, so you can't access a animal class reference to the member variable inside the dog class, * although you're pointing to an instance object of subclass dog, because the subclass dog inherits from the parent class animal, * So when new comes out of a subclass object, the subclass object contains a parent object, * so this a is pointing to the parent object inside the subclass object, so even though a is a reference to the Dog class object, * But in the compiler's eyes you're just an ANI.         The reference object of the Mal class, you can only access the member variables that are in the animal class, and you cannot access any of them.         * Therefore a reference to a parent class (base Class) object is not available to access the newly added members (properties and methods) of its child class object. */        //System.out.println (a.furcolor);System.out.println (String.Format ("A points to dog,a instanceof animal result is%s", ainstanceofAnimal));//true        /*** It is true that "A is a dog" is judged here.         * Because instanceof explores what your whole object actually is, * it's not judged by what you cite as what you see. */System.out.println (String.Format ("A instanceof Dog's result is%s", ainstanceofDOG));//true        /*** Here the cast is used to transform the reference object A to the animal class to a reference to the dog class object, so the transformed Reference object D1 can directly access the new members in the Dog class object. */Dog D1=(Dog) A; System.out.println (D1.furcolor);//Yellow    }}

A instanceof Animal--true
C instanceof Animal--true
D instanceof Animal--true
A instanceof Cat--false
Bigyellow
A pointing to dog,a instanceof Animal The result is true
A instanceof Dog's result is true
Yellow

Memory Analysis:

As you can see in memory, the reference object A that points to the Dog class instance object A is a reference type of animal type, which is interesting, the animal type points to the object of dog, then, in the program's eyes, the dog is regarded as an ordinary animal, Since the dog is regarded as an ordinary animal, then the member variables declared in the dog class Furcolor cannot be accessed because there is no such member variable in the animal class. Therefore, in the strict sense, this a eye only see the child object inside the parent class object animal, so can be accessed is only this animal object inside the Name property, and this animal object outside the Furcolor property is not accessible, Although the dog object does have this attribute exists, but a is not see, a door to see dog--dog look flat, do not know the dog and Furcolor this attribute exists, so a cannot access Furcolor attribute, so from the strict sense, A is pointing to the animal object inside the dog object, which is the yellow arrow pointing to the part, a only see the dog inside this part, and the outside of the dog is not visible. This is the parent reference to the child class object, when the parent refers to the subclass object, it sees only the properties and methods that are owned by the part of the parent class, and it is not seen as part of the subclass.

If you really want to access the Furcolor property of the Dog object, use the object transformation method to transform the reference of the parent object into a reference to the subclass object. Dog D1 = (dog) A; Here is the method of object transformation, to cast a into a reference to a dog object, and then assign this reference to the dog-type reference variable d1, so that D1 and a are pointing to the dog object in the heap memory, and D1 points to all the parts of the dog, and through this D1 you can access all the members of the dog object.

Example two:

 Public classTestclasscast { Public voidF (Animal a) {System.out.println (a.name); if(AinstanceofCat) {Cat Cat=(Cat) A; System.out.println (Cat.eyecolor+ "Eye"); }Else if(AinstanceofDog) {Dog Dog=(Dog) A; System.out.println (Dog.furcolor+ "Fur"); }    }        /**     * @paramargs*/     Public Static voidMain (string[] args) {Animal a=NewAnimal ("name"); Cat C=NewCat ("CatName", "Blue"); Dog D=NewDog ("Dogname", "BLACK"); Testclasscast Testclasscast=NewTestclasscast ();        Testclasscast.f (a);        TESTCLASSCAST.F (c);    TESTCLASSCAST.F (d); }}

The code here is a continuation of the three class Animal,dog,cat tests previously declared, and here we test the three classes inside the Testclasscast class, where we have a new Testclasscast object in the Testclasscast class. , in order to invoke the F (Animal a) method declared in the Testclasscast class, the parameter type in the F () method is the Animal type, and if it is a parameter of the Animal type, then we can pass the subclass object of this Animal type as a parameter. This is possible. It is possible to throw a dog or a cat into the F () method, because dog and cat are also animal. So when the program executes to TESTCLASSCAST.F (a), TESTCLASSCAST.F (c);, Testclasscast.f (d); When the parameter inside the F () method is of type animal, So we can pass in a animal object, in addition, we can also directly inherit from the animal class dog and cat classes inside the dog and cat objects as arguments passed, that is, the animal type of sub-class objects as parameters. This shows that the inheritance and the parent class object reference can point to the benefit of the subclass object, if there is no inheritance relationship exists, if the parent class reference can not point to the subclass object, then we have to define the Test class three F () method, that is to define such an F () method:
F (Animal a), F (Dog D), F (cat C) are used to deal with Animal, Dog and Cat respectively, using three methods to process, the future expansion of the program is not very easy, because object-oriented can help us in the past years of programming the pursuit of a realm is better extensibility. A good example of scalability is that when you build a good one building or after you have written the program, you have built the main building, and in the future you want to add some other functions, try not to modify the main structure, which is called extensibility, you built a building, you now have to add a kitchen next to the building , then you're going to have a lid on it, and if someone tells you I'm adding a kitchen I need to tear down all the main pillars of your building and cover it again. If the structure is designed like this, it is poorly designed and not scalable. So if the F () method is to be written into three overloaded f () methods, then I have to add an F (Bird B) method to handle the birds in the future when I output a bird. This is too much of a hassle to expand, because each animal is treated with a new method, but if there is an inheritance relationship, if the parent object's reference can point to the subclass object, then the extension is simple, you can write the method of handling the animal in a method F (Animal a) is enough, Because all species of animals inherit from the Animal class, it is possible to pass the Animal type parameter to the F () method directly into the subclass object of the Animal class, so that I can call the F (Animal a) method to deal with the output of any animal. This extensibility is much better than adding a new processing method each time, which is one of the benefits of inheritance, which is the benefit of object transformation for Extensibility: "Object references can point to subclass objects" because of the existence of such an inheritance relationship in object-oriented programming, which makes the program more extensible.

  Object Transformation enables a reference to a parent class object to point to a subclass object, giving the program a good extensibility: we can define a reference to the parent class in the parameters of a method, and then actually pass the object as a subclass. Then we can judge in the method which subclass the passed-in object belongs to, then execute the method inside the subclass or call the member variables inside the subclass, so the extensibility of the program is better than the multiple methods defined separately. However, this extensibility has not yet reached its best, and using polymorphism allows the program to achieve maximum scalability.

Object Transformation of basic Java learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.