Type conversion and dynamic binding of Java Polymorphic objects

Source: Internet
Author: User

Type conversions for Java polymorphic objects
The object type conversion referred to here refers to an object that has an inheritance relationship, not an object of any kind. The Java runtime throws a Java.lang.ClassCastException exception when coercion casts on objects that do not have an inheritance relationship.

In the inheritance chain, we convert the subclass to the parent class as "up transformation" and the parent class to the subclass transformation called "down transformation".

Many times, we define a variable as the type of the parent class, but refer to the object of the subclass, which is the process of upward transformation. When the program runs, it implements the invocation of a subclass method by dynamic binding, that is, polymorphism.

Sometimes, however, in order to accomplish something that the parent class does not have, we need to turn the object of the upward transformation into a subclass, calling the method of the subclass, which is the downward transformation.

Note: You cannot cast an object of the parent class directly to a subclass type, but you can only convert the sub-class object that is being transformed to a subclass type again. In other words, the subclass object must be transformed upward before it can be transformed downward. Take a look at the following code:

12345678910111213 public class Demo { public static void main(String args[]) { SuperClass superObj = new SuperClass(); SonClass sonObj = new SonClass(); // 下面的代码运行时会抛出异常,不能将父类对象直接转换为子类类型 // SonClass sonObj2 = (SonClass)superObj; // 先向上转型,再向下转型 superObj = sonObj; SonClass sonObj1 = (SonClass)superObj; }}class SuperClass{ }class SonClass extends SuperClass{ }

Remove the comment from line 7th, and the runtime throws an exception, but the compilation can pass.

Because there is a risk of a downward transition, be sure to use the instanceof operator to determine if the object is the subclass you want when you receive a reference to the parent class, see the following code:

123456789101112131415161718192021 public class Demo { public static void main(String args[]) { SuperClass superObj = new SuperClass(); SonClass sonObj = new SonClass(); // superObj 不是 SonClass 类的实例 if(superObj instanceof SonClass){ SonClass sonObj1 = (SonClass)superObj; }else{ System.out.println("①不能转换"); } superObj = sonObj; // superObj 是 SonClass 类的实例 if(superObj instanceof SonClass){ SonClass sonObj2 = (SonClass)superObj; }else{ System.out.println("②不能转换"); } }}class SuperClass{ }class SonClass extends SuperClass{ }

Operation Result:

1 ①不能转换

Summary: Object type conversions are checked at program run time, the upward transformation is automatic, and the object that is transitioning down must be a subclass of the current reference type.

Java polymorphism and dynamic binding
In Java, a variable of the parent class can refer to an instance of the parent class, or it can refer to an instance of the child class.

Readers should look at a piece of code first:

1234567891011121314151617181920212223242526272829 public class Demo { public static void main(String[] args){ Animal obj = new Animal(); obj.cry(); obj = new Cat(); obj.cry(); obj = new Dog(); obj.cry(); }}class Animal{ // 动物的叫声 public void cry(){ System.out.println("不知道怎么叫"); }}class Cat extends Animal{ // 猫的叫声 public void cry(){ System.out.println("喵喵~"); }}class Dog extends Animal{ // 狗的叫声 public void cry(){ System.out.println("汪汪~"); }}

Operation Result:

123 不知道怎么叫喵喵~汪汪~

The above code defines three classes, namely, Animal, Cat, and Dog,cat, and the Dog class are inherited from the Animal class. The type of the obj variable is Animal, which can point to an instance of the Animal class or to an instance of the Cat and the Dog class, which is correct. That is, a variable of the parent class can refer to an instance of the parent class, or it can refer to an instance of the child class. Note that the reverse is wrong, because all cats are animals, but not all animals are cats.

It can be seen that obj can be either a human or a cat or a dog, it has different manifestations, which is called polymorphism. Polymorphism means that a thing has a different manifestation or form.

Again such as "human", there are many different expression or realization, TA can be a driver, teacher, doctor, etc., you hate yourself when you will say "Next life again," then you become a driver, teachers, doctors can, we say "human" with polymorphism.

There are three prerequisites for polymorphic existence: To have inheritance, to have overrides, to refer to a subclass object as a parent class variable.

When calling a method using Polymorphic mode:
First check whether the method is in the parent class, if not, compile the error, and if so, check whether the subclass overrides the method.
If the child class overrides the method, the method of the subclass is called, otherwise the parent class method is called.

As can be seen from the above example, one of the benefits of polymorphism is that when subclasses are relatively long, there is no need to define multiple variables, you can define only one variable of a parent class type to refer to instances of different subclasses. Take another look at the following example:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 public class Demo { public static void main(String[] args){ // 借助多态,主人可以给很多动物喂食 Master ma = new Master(); ma.feed(new Animal(), new Food()); ma.feed(new Cat(), new Fish()); ma.feed(new Dog(), new Bone()); }}// Animal类及其子类class Animal{ public void eat(Food f){ System.out.println("我是一个小动物,正在吃" + f.getFood()); }}class Cat extends Animal{ public void eat(Food f){ System.out.println("我是一只小猫咪,正在吃" + f.getFood()); }}class Dog extends Animal{ public void eat(Food f){ System.out.println("我是一只狗狗,正在吃" + f.getFood()); }}// Food及其子类class Food{ public String getFood(){ return "事物"; }}class Fish extends Food{ public String getFood(){ return "鱼"; }}class Bone extends Food{ public String getFood(){ return "骨头"; }}// Master类class Master{ public void feed(Animal an, Food f){ an.eat(f); }}

Operation Result:

123 我是一个小动物,正在吃事物我是一只小猫咪,正在吃鱼我是一只狗狗,正在吃骨头

The Master class's Feed method has two parameters, namely the Animal type and the food type, because it is the parent class, so you can pass an instance of the subclass to it so that the master class does not need multiple methods to feed the different animals.
Dynamic binding

To understand the nature of polymorphism, let's talk about the detailed flow of Java invocation methods.

1) The compiler looks at the declaration type and method name of the object.

Assume that you call Obj.func (param), and obj is an object of the Cat class. It is important to note that there may be multiple methods with the name Func but not the same parameter signature. For example, there may be method func (int) and func (String). The compiler will enumerate through all the methods named Func in all Cat classes and its parent class Animal, which has a public access property called Func.

In this way, the compiler obtains a list of all the candidate methods that might be called.

2) Next, the codec will check the parameter signature provided when calling the method.

Select this method if there is a method in all methods named Func that exactly matches the supplied parameter signature. This process is called overload resolution (overloading resolution). For example, if you call func ("Hello"), the compiler chooses the func (String) instead of the func (int). Because of the existence of an automatic type conversion, such as an int that can be converted to a double, if no method is found that is the same as calling the method parameter signature, the type conversion is performed and then the lookup continues, if there is no matching type at all, or if more than one method matches it, then the compilation error.

In this way, the compiler obtains the method name and parameter signatures that need to be called.

3) If the modifier of a method is private, static, final (static and final will be explained later), or is a constructor method, then the compiler will be able to know exactly which method should be called, and we call this called static binding binding).

By contrast, the method that is called relies on the actual type of the object and implements dynamic binding at run time. For example, if func ("Hello") is called, the codec will generate an instruction called Func (String) in a dynamically bound manner.

4) When the program is running and the method is invoked with dynamic binding, the JVM must invoke the method of the class that is most appropriate for the actual type of the object referenced by obj. We have assumed that the actual type of obj is cat, which is a subclass of Animal, which is called if Func (String) is defined in cat, otherwise it will be found in the Animal class and its parent class.

Each time the method is called for a search, the overhead is considerable, so the JVM has previously created a method lable for each class that lists the names of all the methods, the parameter signatures, and the classes to which they belong. This way, when the method is actually called, the virtual machine looks for the table only. In the example above, the JVM searches the Cat class's method table to find a method that matches the call to func ("Hello"). This method may be either Cat.func (string) or Animal.func (string). Note that if you call Super.func ("Hello"), the compiler will search the method table of the parent class for a row.

Assuming that the Animal class contains the three methods of Cry (), GetName (), Getage (), then its method table is as follows:
Cry (), Animal.cry ()
GetName (), Animal.getname ()
Getage (), Animal.getage ()

In fact, Animal also has the default parent class object (which will be explained later), which inherits the method of object, so the methods listed above are not complete.

Assuming the Cat class overrides the Cry () method in the Animal class, and a new method Climbtree () is added, its argument list is:
Cry (), Cat.cry ()
GetName (), Animal.getname ()
Getage (), Animal.getage ()
Climbtree (), Cat.climbtree ()

At run time, the process of calling the Obj.cry () method is as follows:
The JVM first accesses the method table of the actual type of obj, possibly a method table for the Animal class, or a method table for the Cat class and its subclasses.
The JVM searches the method table for a method that matches the cry () and, when found, knows which class it belongs to.
The JVM calls the method.

Type conversion and dynamic binding of Java Polymorphic objects

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.