Semi-deep understanding of Java attribute inheritance

Source: Internet
Author: User

A few days ago in the interview was asked a question, "What is the difference between Java rewrite and overloading?" ”。 This problem in the Java field is a cliché, in fact I think these two things in addition to the Chinese name is very similar (English name seems to be similar), the basic is not a half gross money relationship. It's hard for us to find out their similarities, but we have to try to find the difference between them, hehe.


However, the theme of this article is not rewriting and overloading, but rewriting the twin brother, attribute inheritance.
The beginning of the story, let's look at a code first

1  Public classparent{2  PublicString color;3  PublicParent () {4  This. color= "Green";5 }6  Public voidPrintcolor () {7 System.out.println (color);8 }9  Public Static voidMain (String args[]) {Ten NewChild (). Printcolor (); One } A } - classChildextendsparent{ -  PublicString color; the  PublicChild () { - } -  Public voidPrintcolor () { - System.out.println (color); + } -}

This code is simple, we first wrote a class parent, added a property color to him, and initialized it to "green" in the constructor, and provided a print function to output the value of color.
We then wrote a child class that inherits the parent, overrides the Color property, and overrides the printing method.
We create a child object inside the main function and call the Printcolor method.
So what is the result of the output?


the answer is NULL.


Many people will ask that you have no initialization color for the child class constructor, and how can you have a value.
Slow down, let's change the code.

 Public classparent{ PublicString color; PublicParent () { This. color= "Green";} Public voidPrintcolor () {System.out.println (color);} Public Static voidMain (String args[]) {NewChild (). Printcolor ();}}classChildextendsparent{ PublicString color; PublicChild () {}}

In this code we just erase the Printcolor method of the subclass. Run, the result is green. Things are not as simple as that. In fact, there are three key points in the matter.

    • is the construction method of the parent class called when the subclass object is created?
    • When the parent and child classes have the same properties, are they overwritten or co-exist?
    • Who is the color in the parent class and subclass Printcolor method? The parent class or the child class?

Let's go one by one, first of all, the order in which the constructor is called when inheriting.
Yes, in almost all languages, if you want to run a piece of code correctly, the prerequisite is that all dependencies on this code will work. So, before you fix a piece of code, take care of his dependencies first. For example, when we load a class, we load all the other classes that are referenced in the completed class first. Object creation is also the same, when we create an object, the first task is to "create a parent class object", the parent class is the construction method called at this time.
What happens when we "create a parent class object" and then obviously encounter a problem when the parent object creates and initializes all the properties, and then the subclass intends to create the same property again?
The answer is: Instead, create a second property.

So a subclass object has two properties with the same name, one that is created by the parent class and initialized to green, and a color of a subclass that has not yet been initialized. So which is the color in the Printcolor method?
Here are the first two rules:

1. "Search Step by step, find then stop". This rule can be applied to both properties and methods. His main idea is that when we need to call a method or property, we first see if we have, if not, go to the superior (parent class) to find, until we find it. This can also be a good way to explain how the method overrides are implemented. However, there are a few differences between properties and methods, when a subclass object is transformed upward into a parent class object, the call to a method call of the same name can only be a subclass method, and the calling property invokes the parent class property.
2. Whose method is called, and who is the starting point for the property lookup. The point of this rule is to determine who is calling the method. When a subclass overrides a parent class method, the call must be a subclass method, and conversely, the method of the parent class must be called.
The above two points seem very easy to understand, now let's combine the previous code to understand.
The first piece of code when we call the Printcolor method.

    • 1. To find the Printcolor method in the child object first, it is easy to find it in the child class, so the method called must be the method in the child class.
    • 2. Look for the Color property, because the child class already has a color attribute, and the attribute is first found and stopped to continue searching, printing out, null.

The second piece of code

    • 1. First find the Printcolor method, found that can not find, so go to the parent class to find.
    • 2. Found the Printcolor method in the parent class, stop the lookup.
    • 3. Find the Color property, because the calling method of the parent class, all property lookup starting point is the parent class object, in the parent class object successfully found a color initialized to green
    • 4. Print out Green

If you understand the above two processes, then you are basically mastering the attribute inheritance. Summarize the key points.

    1. When a parent class subclass has the same attributes, it is added rather than overwritten on the parent class.
    2. Methods and properties are called from the current class and are looked up from the beginning. Stop when you find it.
    3. Who is calling the method, and who is the starting point for the lookup. Therefore, it is important to determine exactly which class is the method.

Question 1: What happens when we are in the first paragraph of code and want to call the parent class's Color property to print the Green method ?

With Super.color, you can access

Similarly, the Printcolor () method of the parent class can be called using Super.printcolor ().

Question 2: If the hierarchy parent also has a parental class perparent also has the same properties, how can we call the child?
Super.super.color?
Obviously wrong.

At this point we just have to move up. (perparent) Child.color;

It is important to note, however, that after the method is overridden, using (parent) Child.printcolor () is inaccessible to the parent class method.

The end of the article, I left two problems, if you look at a correct answer, I can only silently brush for you 66 6666.

Question 1:

 Public classparent{ PublicString color; PublicParent () { This. color= "Green";} Public voidPrintcolor () {System.out.println (color);} Public Static voidMain (String args[]) {NewChild (). Printcolor ();}}classChildextendsparent{//We'll remove the color attribute here//public String color; PublicChild () {} Public voidPrintcolor () {System.out.println (color);}}

Question 2:

 Public classparent{ PublicString color; PublicParent () { This. color= "Green";}//Remove the Printcolor method from the parent class here/*Public void Printcolor () {System.out.println (color);}*/ Public Static voidMain (String args[]) {NewChild (). Printcolor ();}}classChildextendsparent{//We'll remove the color attribute here//public String color; PublicChild () {} Public voidPrintcolor () {System.out.println (color);}}

Semi-deep understanding of Java attribute inheritance

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.