"Go" parent class reference to child class object

Source: Internet
Author: User

A parent class reference to a subclass object refers to:

For example, parent class animal, subclass Cat,dog. Where animal can be either a class or an interface, cat and dog are subclasses that inherit or implement animal.

Animal Animal = new Cat ();

That is, the parent class is declared, which actually points to an object of the subclass.

So what are the advantages of using this? You can use these keywords to summarize: polymorphic, dynamic link, upward transformation

It is also said that this is interface-oriented programming, you can reduce the coupling of the program, that is, the caller does not have to care about which object to invoke, only need to programming for the interface can be, the callee is completely transparent to the caller. Let you focus more on what the parent can do without caring about how the subclass is done, and you can replace a subclass at any time, that is, replacing a specific implementation at any time without modifying the other.

Future combinations of design patterns (such as Factory mode, proxy mode) and reflection mechanisms may have a deeper understanding.

The following describes the polymorphism of Java and the dynamic link in it, which is transformed upward:

Object-oriented three features: encapsulation, inheritance and polymorphism;

Encapsulation hides the internal implementation mechanism of the class, it can modify the internal structure of the class without affecting the user, while protecting the data;

Inheritance is to reuse the parent class code, and the subclass inherits the parent class to have the members of the parent class.

the overrides, overloads, and dynamic joins of a method are polymorphic. Java introduces the concept of polymorphism, one of the reasons is that it is in the inheritance of the class and C + +, which allows multiple inheritance, which does give it a very powerful function, but the complex inheritance of the C + + developers have also brought greater trouble, in order to avoid the risk, Java only allow single inheritance, There is a is-a relationship between the derived class and the base class (that is, "cat" is a "animal"). Although this ensures that the inheritance relationship is simple and clear, but there is bound to be a large number of functional limitations, so Java introduced the concept of polymorphism to compensate for this shortcoming, in addition, abstract classes and interfaces are also important means to solve the single inheritance restrictions. At the same time, polymorphism is also the essence of object-oriented programming.

Understanding polymorphism is the first thing to know about "upward transformation".

I defined a subclass cat, which inherits the animal class, and the latter is the parent class. I can pass

Cat C = new Cat ();
Instantiating a cat object is not difficult to understand. But when I define this:

Animal a = new Cat ();
What does that mean?

Very simply, it means I have defined a reference to the animal type, pointing to the new cat type object. because Cat is inherited from its parent class animal, references to animal types can point to objects of the cat type. This is the "upward transformation".

So what's the point of doing that? Because subclasses are an improvement and an extension to the parent class, the generic subclass is more powerful than the parent class, the property is more unique than the parent class, and the object that defines a reference to a child class of a parent class can use both the powerful functions of the subclass and the commonality of the parent class. Therefore, a reference to a parent class type can invoke all the properties and methods defined in the parent class, whereas a method that is not in the parent class defined in the subclass cannot be called by a parent class reference;

What is a dynamic link? When a method in a parent class is defined in a parent class and not overridden in a subclass, it can be called by a reference to the parent class type, and for a method defined in the parent class, if the method is overridden in a subclass, a reference to the parent class type will invoke this method in the subclass, which is the dynamic join.

Here's a look at a typical polymorphic example:

[Java]View Plaincopy
  1. Class father{
  2. Public void Func1 () {
  3. Func2 ();
  4. }
  5. This is the Func2 () method in the parent class, because the method is overridden in the following subclass
  6. So when called in a reference to a parent class type, this method is no longer valid
  7. Instead, the Func2 () method that will be overridden in the calling subclass
  8. Public void Func2 () {
  9. System.out.println ("AAA");
  10. }
  11. }
  12. Class child extends father{
  13. func1 (int i) is an overload of the Func1 () method, not primarily a rewrite!
  14. Because this method is not defined in the parent class, it cannot be called by a reference of the parent class type
  15. So in the following Main method, CHILD.FUNC1 (68) is wrong.
  16. Public void func1 (int i) {
  17. System.out.println ("BBB");
  18. }
  19. Func2 () overrides the Func2 () method in the parent class father
  20. If the Func2 () method is called in a reference to the parent class type, then this method must be overridden in the subclass
  21. Public void Func2 () {
  22. System.out.println ("CCC");
  23. }
  24. }
  25. Public class Polymorphismtest {
  26. Public static void Main (string[] args) {
  27. Father child = new Child ();
  28. Child.func1 (); //What will the printed result be?
  29. Child.func1 (a);
  30. }
  31. }
[Java]View Plaincopy
  1. Class father{
  2. public void Func1 () {
  3. Func2 ();
  4. }
  5. //This is the Func2 () method in the parent class, because the method is overridden in the following subclass
  6. //So when called in a reference to a parent class type, this method will no longer be valid
  7. //replaced by the Func2 () method that will be overridden in the calling subclass
  8. public void Func2 () {
  9. System.out.println ("AAA");
  10. }
  11. }
  12. Class child extends father{
  13. //func1 (int i) is an overload of the Func1 () method, not primarily a rewrite!
  14. //Because this method is not defined in the parent class, it cannot be called by a reference of the parent class type
  15. //So CHILD.FUNC1 (68) is wrong in the main method below
  16. public void func1 (int i) {
  17. System.out.println ("BBB");
  18. }
  19. //func2 () overrides the Func2 () method in the parent class Father
  20. //If the Func2 () method is called in a reference to a parent class type, then this method must be overridden in a subclass
  21. public void Func2 () {
  22. System.out.println ("CCC");
  23. }
  24. }
  25. Public class Polymorphismtest {
  26. public static void Main (string[] args) {
  27. Father child = new Child ();
  28. Child.func1 ();    //What will the printed result be?
  29. CHILD.FUNC1 (68);
  30. }
  31. }

The above procedure is a very typical polymorphic example. Subclass Child inherits the parent class father and overloads the Func1 () method of the parent class, overriding the Func2 () method of the parent class. The overloaded func1 (int i) and func1 () are no longer the same method, and because there is no func1 (int i) in the parent class, the reference child of the parent class type cannot call the func1 (int i) method. When the subclass overrides the Func2 () method, the reference to the parent class type will call the FUNC2 () overridden in the subclass when calling the method.

So what kind of results will the program print?
Obviously, it should be "CCC".

For polymorphism, the following points can be summed up:

One, a reference to the child class using the parent class type;
Second, the reference can only invoke methods and variables defined in the parent class;
Thirdly, if a method in the parent class is overridden in a subclass, the method in the subclass is called when the method is called; (dynamic connection, dynamic invocation)
Variables cannot be overridden (overwritten), the concept of "overriding" is only for methods, and if a variable in the parent class is "overridden" in a subclass, an error is made at compile time.

PS: This piece is tried, not shown save, he will show whether the variable is from the parent class or the child class

Also reproduced:

Polymorphism is through:
1 interfaces and implements the interface and overrides several different classes of the same method in the interface embodied by
2 The parent class and the inherited parent class are implemented by overwriting several different subclasses of the same method in the parent class.

First, the basic concept

Polymorphism: Sends a message to an object, allowing the object to decide for itself what behavior to respond to.
A dynamic method call is implemented by assigning a subclass object reference to a superclass object reference variable.

This mechanism of Java follows a principle:when a Superclass object reference variable refers to a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class.

1. If a is a reference to Class A, then a can point to an instance of Class A, or to a subclass of Class A.
2. If a is a reference to interface A, then a must point to an instance of a class that implements interface A.


Second, Java polymorphism Implementation mechanism

Sun's current JVM implementation mechanism, a reference to a class instance, is a pointer to a handle (handle), which is a pair of pointers:
A pointer to a table, and in fact the table has two pointers (one pointer to a method table containing the object, and another to the class object, indicating the type to which the object belongs);
Another pointer points to a piece of memory space allocated from the Java heap.

Iii. Summary

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:
* Why can object instances of a subclass's type be covered by a superclass reference?
Auto-enable up-shift. Through this statement, the compiler automatically moves the subclass instance up to become a generic type baseclass;
* A.play () will execute the subclass or the method defined by the parent class?
Sub-class. At run time, the actual type is referenced according to the object of a to obtain the corresponding method. So there is polymorphism. A base class object reference, which is given a different subclass object reference, behaves differently when the method is executed.

In A1=c2, there are 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 complex rule, a type reference can only reference the reference type itself contains methods and variables.
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.

Four. Example: A behavior, different objects, they are specifically reflected in the way they are not the same,
Example: Method overload overloading and method override (overwrite) override
Class human{
void Run () {The output person is running}
}
Class Man extends human{
void run () {Output man running}
}
This time, the same is run, different objects, not the same (this is the method covered by the example)
Class test{
void out (String str) {output str}
void out (int i) {Output i}
}
This example is a method overload with the same method name and a different parameter table

OK, understand that these are not enough, but also employing in the running example
Human ahuman=new Man ();
So I'm going to instantiate a man's object and declare a human reference, and let it point to the man object.
It means that the man is the object of human to see.

Like going to the zoo, you see an animal, you don't know what it is, "What kind of animal is this?" "It's a giant panda!"
These 2 words, is the best proof, because do not know it is the panda, but know its parent class is an animal, so,
This Panda object, you see it as the father of the animal look, this looks reasonable.

In this way, notice that the new Man () is instantiated, so the Ahuman.run () method outputs "men running."

If under subclass man you write some of its unique methods such as Eat (), and human does not have this method, when calling the Eat method, be sure to pay attention to the coercion type conversion ((man) Ahuman). Eat (), so you can ... For the interface, the situation is similar ...

[Java]View Plaincopy
  1. Instance:
  2. Package domatic;
  3. Defining Superclass SuperA
  4. Class SuperA {
  5. int i = + ;
  6. void Fun (int j) {
  7. j = i;
  8. System.out.println ("This is SuperA");
  9. }
  10. }
  11. Defines subclasses of SuperA Subb
  12. Class Subb extends SuperA {
  13. int m = 1;
  14. void fun (int aa) {
  15. System.out.println ("This is Subb");
  16. }
  17. }
  18. Defines subclasses of SuperA SUBC
  19. Class SUBC extends SuperA {
  20. int n = 1;
  21. void Fun (int cc) {
  22. System.out.println ("This is SUBC");
  23. }
  24. }
  25. Class Test {
  26. Public static void Main (string[] args) {
  27. SuperA a = new SuperA ();
  28. Subb B = new Subb ();
  29. SUBC C = new SUBC ();
  30. A = b;
  31. A.fun (+);
  32. A = C;
  33. A.fun ($);
  34. }
  35. }
 


/*
* Subb and SUBC are subclasses of superclass SuperA in the above code, we declare 3 reference variables a, B in class test,
* C to implement a dynamic method call by assigning a subclass object reference to a superclass object reference variable. Maybe someone will ask:
* "Why (1) and (2) Not output: This is SuperA".
* This mechanism of Java follows a principle: When a Superclass object references a variable that references a subclass object,
* The type of the referenced object instead of the reference variable determines whose member method is called.
* But this called method must be defined in the superclass,
* That is, the method covered by the quilt class.
* Therefore, do not be confused by the example above (1) and (2), although written A.fun (), but because (1) A is assigned by B,
* Points to an instance of subclass Subb, so (1) the called Fun () is actually the member method of the subclass Subb Fun (),
* It overrides the member method of the superclass SuperA Fun (); similarly (2) the member method of the subclass SUBC is called Fun ().
* Also, if a subclass inherits a superclass that is an abstract class, although the abstract class cannot be instantiated by the new operator,
* However, you can create an object reference to an abstract class that points to a subclass object for run-time polymorphism. The specific implementation of the above example.
* However, subclasses of an abstract class must override all the abstract methods in the implementation superclass,
* Otherwise the subclass must be decorated with the abstract modifier, and of course it cannot be instantiated.
*/



1.JAVA does not have many inheritance, a class can have a parent class. The manifestation of inheritance is polymorphism. A parent class can have more than one subclass, whereas in subclasses you can override the parent class's methods (for example, method print ()) so that the code that is overridden in each subclass is different and the natural representation is different. This uses the parent class's variable to refer to the different subclasses, the result and the representation of the same method print () is different, this is polymorphic, the same message (that is, call the same method) will have the same result. To illustrate:

[Java]View Plaincopy
  1. Parent class
  2. Public class father{
  3. Parent class has a child-fighting method
  4. Public void Hitchild () {
  5. }
  6. }
  7. Sub-Class 1
  8. Public class Son1 extends father{
  9. Overriding parent class hitting kids method
  10. Public void Hitchild () {
  11. System.out.println ("Why hit me?") What have I done wrong! ");
  12. }
  13. }
  14. Sub-Class 2
  15. Public class Son2 extends father{
  16. Overriding parent class hitting kids method
  17. Public void Hitchild () {
  18. System.out.println ("I know wrong, don't fight!" ");
  19. }
  20. }
  21. Sub-Class 3
  22. Public class Son3 extends father{
  23. Overriding parent class hitting kids method
  24. Public void Hitchild () {
  25. System.out.println ("I run, you can't fight!" ");
  26. }
  27. }
  28. Test class
  29. Public class test{
  30. Public static void Main (String args[]) {
  31. Father Father;
  32. Father = new Son1 ();
  33. Father.hitchild ();
  34. Father = new Son2 ();
  35. Father.hitchild ();
  36. Father = new Son3 ();
  37. Father.hitchild ();
  38. }
  39. }
 


All call the same method, and there are different results! This is the manifestation of polymorphism.

The above example is a simple embodiment of the factory model

"Go" parent class reference to child class object

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.