Java inherits internal class issues (Java programming thought notes)

Source: Internet
Author: User

The normal inner class holds a reference to the owning external class by default. If a new class is defined to inherit the inner class, how is the "secret" reference initialized?

Java provides a special syntax:

1 classEGG2 {2      Public classyolk{3          Publicyolk () {4System.out.println ("Egg2.yolk");5         }6     }7 }8 classBIGEGG2 {9      Public classYolkextendsEgg2.yolk {Ten          Publicyolk () { One         } A     } -}

Above this code compilation cannot pass, the error is in 10 lines, the error is:

No enclosing instance of type EGG2 is available due to some
Intermediate constructor invocation

Modify the code to:

1 classEGG2 {2      Public classyolk{3          Publicyolk () {4System.out.println ("Egg2.yolk");5         }6     }7 }8 classBIGEGG2 {9      Public classYolkextendsEgg2.yolk {Ten          PublicYolk (Egg2 egg2) { OneEgg2.Super() ; A         } -     } -}

Egg2.super () was added in line 11, so the compilation passed the ~~

Then look at another piece of code that seems to contradict the above conclusion:

1 classEGG2 {2      Public classyolk{3          Publicyolk () {4System.out.println ("Egg2.yolk");5         }6     }7 }8 classBigEgg2extendsEGG2 {9      Public classYolkextendsEgg2.yolk {Ten          Publicyolk () { One         } A     } -}

Note that 8 rows of inheritance and 11 rows do not use the Super statement, but this code compiles properly, why?

I guess the reason:

The super syntax is used to get the derived class to obtain a reference to the perimeter class, that is, to get the Bigegg2.yolk Class A reference to EGG2. Looking at the code above, BigEgg2 inherits from Egg2, so BIGEGG2 has a reference to EGG2.

Bigegg2.yolk is the inner class of BigEgg2, so yolk implicitly holds a reference to BIGEGG2, so through this reference chain, Bigegg2.yolk has a reference to EGG2. So you don't need to use super syntax.

Java inherits internal class issues (Java programming thought notes)

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.