Java object type conversions and polymorphism

Source: Internet
Author: User
Tags diff

Object Type Conversions

It is divided into upward transformation and downward transformation (forced object transformation). an upward transformation is the process by which a child object transforms into a parent object, such as a cat class to an animal; a downward transition is a forced transformation of a parent object to a child object. This is similar to the conversion of the underlying data type, where byte is automatically converted to int (up), and int can be coerced to byte (downward transition).

For object transformation, a member that is unique to a child object will not be accessible after an upward transformation . It means that when you need an animal, you can pass it on as an animal, because the cat inherits from the animal and the cat has all the properties of the animal. But after the upward transformation, the cat is no longer a cat, but is regarded as an animal, its own unique properties and methods are not visible. In other words, you can only recognize the contents of a parent object after you have transformed it upward.

The reference variable instanceof class name can be used to determine whether the object referred to by the reference variable belongs to a class, that is, "object is not a certain class", such as declaring a cat class object reference "Cat C", and then "C instanceof Animal" The meaning of the expression is "is Object c an animal?" "For objects that return true for instanceof, they can be converted to class objects, but some may need to be cast.

The upward transformation can be done automatically, this is logical, the dog inherits the automatic class, it is an animal in itself, so when the animal class is needed, losing a dog in the past will automatically turn upward into animal class. But then the dog is not a dog, but an animal, so the unique members of the dog are no longer visible.

The cast is the same as the underlying data type cast, with the target type preceded by the object to be converted, for example, animal A is coerced into dog D: Dog d = (Dog)a .

The following is an example of an object type conversion that provides a good analysis of whether you can transform, access certain members after a transformation, and so on.

 class Animal {StringName Animal (StringName) { This. name = name;}} class Cat extends Animal {StringEyecolor; Cat (StringNameStringColor) {Super(name); This. Eyecolor = color;}} class Dog extends Animal {StringFurcolor; Dog (StringNameStringColor) {Super(name); This. Furcolor = color;}} Public class ocast {public staticvoidMainString[] args) {Animal a =NewAnimal ("Animal"); Cat C =NewCat ("Cat","Blue"); Dog d =NewDog ("Dog","BLACK"); System.out.println (AinstanceofAnimal);//return TrueSystem.out.println (cinstanceofAnimal);//return TrueSystem.out.println (dinstanceofAnimal);//return TrueSystem.out.println (AinstanceofCat);//return falseSystem.out.println (A.name);//return AnimalA =NewDog ("Yellowdog","Yellow");//reference variable A is transformed upward, because a is a animal typeSystem.out.println (A.name);//return YellowdogSystem.out.println (AinstanceofAnimal);//return TrueSystem.out.println (AinstanceofDOG);//return True        //system.out.println (A.furcolor); error! Because a is treated as an object of the animal classDog D1 = (dog) A;//Because "a instanceof Dog" is true, you can force a downward transitionSystem.out.println (D1.furcolor);//return Yellow}}

For the above a = new Dog("yellowdog",yellow) , A is the animal type, but at this point it points to the dog object. That is, it is a dog, so it is also the animal class , so a instanceof Animal); and a instanceof Dog; both are true, and this is its "pointer" to the decision. but because its type is the animal type, the type determines what data can be stored and is not visible for existing but non-conforming types of data, so the animal type determines that it sees only the animal part of the dog object . Such as:

Since can be transformed upward, with instanceof logic judgment, can achieve very good extensibility. For example, the Sing (Animal a) method of an animal requires an animal class that can give it a dog D, which is then transformed upward (as if a double type was given an int data), although the actual reference to dog D is still a canine object, so it is if (a instanceof Dog) judged true, The statement that can embody the particularity of the Dog Sing () method is called. If you pass a cat, if you judge and invoke a statement that reflects the specificity of the cat Sing () method. In this way, any time you want to add an animal, you just need to increment an if statement. See the following example:

 class Animal {StringName Animal (StringName) { This. name = name; }} class Cat extends Animal {Cat (StringName) {Super(name);}} class Dog extends Animal {Dog (StringName) {Super(name);}} Public class testcast {public staticvoidMainString[] args) {Testcast T =NewTestcast (); Animal A =NewAnimal ("Animal"); Animal C =NewCat ("Cat"); Animal d =NewDog ("Dog");    T.sing (a); t.sing (c); t.sing (d); }voidSing (Animal a) {if(AinstanceofCAT) {Cat cat = (cat) A; System.out.println ("Cat is singing"); }Else if(AinstanceofDog) {Dog dog = (dog) A; System.out.println ("Dog is singing"); }Else{System.out.println ("Not an instance of animal"); }    }}

If there is no object transformation, then the Sing () is defined in dog, and a sing () is defined in cat. To add an animal, the animal must also define a sing (). Now it is much more convenient to modify the IF statement directly inside the Sing () method.

Note that the Sing () method above is not a method of animal or other subclasses, but rather a separate definition for invocation in other classes.

Polymorphic

The upward transformation, while increasing scalability to some extent, is not too high. Based on the upward transformation, Java's polymorphic implementation is more scalable and convenient.

Polymorphism is also called dynamic binding or late binding, which is a binding made during execution, not a binding during compilation (this is a static binding or a pre-binding).

The principle of polymorphism is that when you call an overridden method after an upward transformation, the parent class method should be called, but the subclass's overridden method is actually called dynamically. In fact, the binding during compilation is really a parent class method, except that it dynamically tunes the class corresponding method during execution.

For example, the Sing () method of the animal class, both the cat and the dog classes override the Sing () method. When a animal object is required and a cat class is passed, the cat's Sing () method is called. The logic for dynamic binding is similar to the following code:

void sing(Animal a) {    if ( a instanceof Cat) {        Cat cat = (Cat)a;        System.out.println("cat is singing");    else if(a instanceof Dog) {        Dog dog = (Dog)a;        System.out.println("dog is singing");    else {        System.out.println("not an instance of animal");    }}

The following is a polymorphic example:

 class Animal {PrivateString name; Animal (String name) { This. name = name;}Public   void sing() {System.out.println ("Animal sing ...");}} class Cat extends Animal {PrivateString Eyecolor; Cat (String n,string c) {Super(n); Eyecolor = C;}Public   void sing() {System.out.println ("Cat sing ...");}} class Dog extends Animal {PrivateString Furcolor; Dog (String n,string c) {Super(n); Furcolor = C;}Public   void sing() {System.out.println ("dog sing ...");}} class Lady {PrivateString name;PrivateAnimal Pet; Lady (String name,animal Pet) { This. name = name; This. Pet = Pet;}Public   void mypetsing() {pet.sing ();}} Public  class Duotai {Public   static void main(String args[]) {Cat c =NewCat ("CatName","Blue"); Dog d =NewDog ("Dogname","BLACK"); Lady L1 =NewLady ("L1", c); Lady L2 =NewLady ("L2", d);        L1.mypetsing ();    L2.mypetsing (); }}

The results of the compiled execution are:

cat sing...dog sing...

In the example above, the method of constructing the Lady class and the code she calls the Sing () method are:

Lady(String name,Animal pet) {thisthis.pet = pet;}public void myPetSing(){pet.sing();}

If the pet that constructs the Lady object is Cat object C, this C will first be transformed upward into the animal class, which means that lady's pet attribute, while pointing to a "Cat C" object, sees only the animal part of the parent object. Then myPetSing(pet.sing();) the method will naturally invoke the Sing () method of the animal class. The above procedure is the process that the compiler considers, and is also the process of static binding or early binding.

However, when the compilation is complete, the pet attribute can only see the animal part, but the actual execution pet.sing () is converted to execute c.sing (). is equivalent to doing an object type cast Cat petx = (Cat)pet . This is the process of dynamic binding or late binding, also known as polymorphism.

In fact, after the object is new, the method it involves is placed in a list of methods in the code segment memory area, which contains the subclasses, the parent class methods, but sometimes invisible methods cannot be called. When executing a program, the internal mechanism can search the method list for the most compliant method and execute it.

The key points for implementing polymorphic technologies are:

    • (1). defines a parent class that refers to F and points it to a subclass object, which is an upward transformation ;
    • (2). override the Parent class's method, and use the parent class to reference F to refer to this method. This allows you to program for the parent class .

As in the example above, pet is defined as a animal class rather than as a specific subclass, and pet.sing () is called in the method. So dependent, there is no need to consider whether pet is Cat/dog, in the function extension to add the bird class, completely no longer modify the Lady Class code.

For example, the parent class animal, subclass Dog, Method Sing ().

 class Animal {Public   void sing(A) ;} class Dog extends Animal {Public   void sing(B) ;} Public  class Test {Animal A =NewDog ();//Parent reference variable a points to child object dog, which will now be transformed upwardA.sing ();//Use the parent class reference variable A to refer to the overridden method sing (), which is dynamically bound to the dog's Sing () when executed}
Reprint Please specify Source: http://www.cnblogs.com/f-ck-need-u/p/7750670.htmlNote: If you think this article is not bad please click on the lower right corner of the recommendation, your support can inspire the author more enthusiasm for writing, thank you very much!

Java object type conversions and polymorphism

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.