Assigning a subclass object reference to a superclass object JAVA compile-time polymorphism

Source: Internet
Author: User

Assigning a subclass object reference to a superclass object JAVA compile-time polymorphism (RPM)(2012-05-10 11:24:05) reproduced
Tags: gossip Category: Also no clear _soft
1. Implement a dynamic method call by assigning a subclass object reference to a superclass object reference variable.

Derivedc c2=new Derivedc ();

BaseClass a1= C2; BaseClass base class, Derivedc is a subclass that inherits from BaseClass

A1.play (); Play () is defined in Baseclass,derivedc, where subclasses overwrite the method

Analysis:

@@@ 为什么 can an object instance of the type of a subclass be covered by a superclass reference?

Auto-enable up-shift. With this statement, the compiler automatically The subclass instance moves up to become a generic type BaseClass

  * * * * * A1.PLAY () will execute subclasses or methods defined by the parent class?

Sub-class.at runtime, the corresponding method is obtained by referencing the actual type according to the A1 object. So there's polymorphism.。 A base class object reference, which is given a different subclass object reference, behaves differently when the method is executed.

At the time of A1=C2, there were still two handles, A1 and C2, But A1 and C2 have the same chunk of data memory and different function tables .

2. You cannot assign a parent object reference to a child class object reference variable

BaseClass a2=new BaseClass ();

Derivedc c1=a2;//Error

   in Java, the upward transformation is automatic, but the downward transformation is not, and requires our own definition to be enforced.

C1= (DERIVEDC) A2; A forced conversion, that is, a downward transformation.

3, remember a very simple and very complex rules,a type reference can only refer to methods and variables that the reference type itself contains.

You might say that the rule is not correct, because the parent class refers to the subclass object, and the last thing you do is subclass the method.

In fact, this is not contradictory, it is because the use of late binding, dynamic operation of the time and according to the type to call the subclass method. If this method of the subclass is not defined in the parent class, an error occurs.

For example, the Derivedc class adds several functions (such as myfun ()) In addition to the functions defined in BaseClass.

Analysis:

When you use a parent reference to refer to a subclass, the JVM has already used the compiler-generated type information to adjust the conversion.

Here you can understand that the equivalent of a function that is not a parent class is set from the virtual function table to be invisible. Note that it is possible that some function addresses in the virtual function table have been rewritten in the subclass, so the virtual function project address in the Object virtual function table has been set to the address of the method body completed in the subclass.

4. Comparison of Java and C + + polymorphism

The JVM support workaround for polymorphism is almost the same as in C + +,

Just a lot of the compiler in C + + is putting type information and virtual function information in a virtual function table, but using some kind of technology to differentiate.

Java opens the type information and function information. After inheritance in Java, subclasses will reset their virtual function tables, and the items in this virtual function table are made up of two parts. Virtual functions that inherit from the parent class and the subclass's own virtual functions.

A virtual function call is called indirectly through a virtual function table, so polymorphism can be achieved.

All of Java's functions, except those declared final, are later bound.

C + + implements polymorphism, using the keyword virtual, in order to cause late binding, the use of virtual functions. If a function is declared as virtual in the base class, then all subclasses are virtual. The redefinition of the virtual function becomes offside.

Interface Parent

{

String method ();

}

Class Child1 implements Parent

{

Public String Method ()

{

return "Child1";

}

}

Class Child2 implements Parent

{

Public String Method ()

{

return "Child2";

}

}

public class Test

{

public static void Main (string[] args)

{

Parent parent = new Child1 ();

System.out.println (Parent.method ());

Parent = new Child2 ();

System.out.println (Parent.method ());

}

}

Output Result:

Child1

Child2

Only multiple subclasses inherit from or implement an interface from a parent class. When these child class instances are established, the parent class or interface is used as the variable type, as in the previous example, parent. That is, the interface that the user corresponds to is a parent. And because the subclass after new is different, the result of calling the same method to return different results is called polymorphic. It is the same method that behaves differently when using different subclasses (here is a different return value).

-------------------------------------------------- --------------------------------------------------- ---------- -------

There are two kinds of polymorphism in Java: Runtime polymorphism and compile-time polymorphism.

A brief introduction to the polymorphism of classes is as follows:

Polymorphism (polymorphism) means that a name can have multiple semantics. In the programming language, polymorphism refers to "one definition, multiple implementations". For example, the operator + has multiple meanings, and exactly what kind of operation depends on the type of operand that participates in the operation:

1+2//addition operator

"1" + "2"//String join operation, operand is string

Polymorphism is one of the core features of object-oriented, and the polymorphism of class provides the flexibility of member design and the multiplicity of method execution in class.

1. Polymorphism of class performance

(1) Method overloading

Overloading behaves as a method's polymorphism in the same class. A class of life multiple overloaded methods provide multiple implementations of a function. At compile time, depending on the data type \ Number and order of the method's actual parameters, decide which of the overloaded methods should be executed.

(2) Subclasses redefine the members inherited from the parent class

Subclasses cannot delete a subclass when they inherit from a parent class, but can redefine them, allowing the Frey members to adapt to the new requirements of the subclass. Subclasses redefine the parent class member, the member of the same name shows polymorphism between the parent class and the child class, the parent class object refers to the parent class member, the subclass object references the child class member, There is no conflict or confusion.

Subclasses can redefine a member variable of the same name as the parent class, which is called a subclass to hide the parent class member variable. Subclasses can also redefine a member method of the same name as the parent class, which is called a subclass method overriding (override) The parent class method when the parameter list of the subclass method is identical to the parent class method parameter list. When overriding a parent class method, the access rights of the subclass method cannot be less than the permissions of the parent class method.

Because the Equals () method of the object class compares the two object references for equality rather than the value equality, a class overwrites the Equals () method of the object class, providing two objects of this class comparing equality methods.

Overrides are manifested by the polymorphism of the method between the parent class and the subclass. Java looks for methods of execution, starting with the class to which the object belongs, looking for a matching method to execute, or, if there is no matching method in the current class, looking up the matching method in the parent class or ancestor class, one by one, until the object class.

2. Super Reference

In a member method of a subclass, you can refer to a parent class member by using the pronoun super. The syntax for super references is as follows:

Super ([parameter list])//In the constructor method body of the subclass, call the constructor of the parent class

Super. Member variables//When a subclass hides a parent class member variable, references a parent-like name member variable

Super. Member method ([parameter list])//When a subclass overrides a parent class member method, call the parent-like member method

* Note: The super reference does not use a separate syntax

3. There are two kinds of polymorphism:

1) Compile-time polymorphism

For multiple methods with the same name, it is called compile-time polymorphism if it is possible at compile time to determine which of the methods in the same name are executed.

2) Run-time polymorphism

If you are not sure at compile time, you can only determine at run time which of several methods with the same name is executed, which is called run-time polymorphism.

-------------------------------------------------- --------------------------------------------------- ---------- -

On the Java polymorphism, some books are said, it tells the Java polymorphism into static polymorphism, and dynamic polymorphism, and so-called static polymorphism is only a function of overloading, dynamic polymorphism is the method of overwrite.

As below:

Class Test

{

void print ()

{

System.out.println ("Hello World");

}

void print (int x)

{

System.out.println ("Hello World" +i);

}

public static void Main (String []args)

{

Test ts=new test ();

Ts.print ();

Ts.print (10);

}

}

  

Dynamic polymorphism:

Class Test

{

void print ()

{

System.out.println ("Hello Test");

}

public static void Main (String []args)

{

A a=new a ();

A.print ();

}

}

Class A extends Test

{

void print ()

{

System.out.println ("Hello A");

}

}

is to assign an instance of a subclass to a parent class, see the following program:

Class A

{

void print () {}

public static void Main (String []args)

{

A [] a=new a[3];

A[0]=new B ();

A[1]=new C ();

A[2]=new D ();

for (int i=0;i<a.length;i++)

{

A[i].print ();

}

}

}

Class B extends A

{

void print ()

{

System.out.println ("Hello B");

}

}

Class C extends A

{

void print ()

{

System.out.println ("Hello C");

}

}

Class D extends A

{

void print ()

{

System.out.println ("Hello D");

}

}

  

In Java, a subclass is an instance of a parent class, which is like saying that fish are animals. But can not say that animals must be fish, which is in line with people's understanding of the real world law. In addition, Java provides us with a keyword, in the xinxin Sun Tutorial also talked about it. It's instanceof.

You can use this to determine whether an object is an instance of a class. Or the above a, B,c, Class D Example:

Write the following code in the Mian function: (delete the original code)

b b=new B ();

if (b instanceof A)

System.out.println ("b instanceof A");

Output: b instanceof A

Description B is an instance of Class A.

Let's look at the following example.

A a=new B ();

if (a instanceof B)

System.out.println ("a instanceof B");

Output: a instanceof B

But not at this time, B b=a;

Although a is an example of B, it cannot be assigned this way, like this:

b b= (b) A;

Carry out Class System.out.println ("a instanceof B");

Assigning a subclass object reference to a superclass object JAVA compile-time polymorphism

Related Article

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.