Why use internal classes in Java

Source: Internet
Author: User
Tags multiple inheritance in java

First, preface
About the inner class of Java, there are too many things to say, this blog can not be described in detail, so pick some focus on the talk. With regard to the use of internal classes, you may wonder why we use internal classes? To answer this question, you need to know something about the inner class. So this article first introduces some of the different things about inner classes, and then answers why we use internal classes. You crossing, the article is a little bit long, deep breath. Come on, let's get started!

Ii. definition of internal class

The inner class definition is very simple, which is to put the definition of one class inside the definition of another outer class. As shown in the following code:

Class Outterclass {class Innerclass {}}

You might think, what's the difference between an inner class and a combination? It's just so simple to put the definition of the inner class inside the outer class, how many things can be caused? Well, you don't have to say, there's really a lot of stuff.

Third, the internal category of those things out of the thing

1. Internal classes can access all members of the perimeter class, including private members.

When an inner class object is generated, there is a connection between this object and the outer class object that made it, so it can access all members of its perimeter class object without any special conditions. As shown in the following code:

Class Outterclass {private int i = 1;class innerclass {public void Displayprivate () {System.out.println (i);}}} public class Mainclass{public static void Main (string[] args) {Outterclass outter =  new Outterclass (); O Utterclass.innerclass inner = outter.new innerclass (); Inner.displayprivate ();}}

As you can see from the code above, the inner class has access to the private member variables of the external class. In this code, it is also important to note that

① generates the inner class object, must first have the periphery class object, concrete practice see Code;

② the inner class can access the private members of the perimeter class, the nested classes in C + + do not have this feature.

2. inner class and static

① inner class cannot contain static method;

The ② inner class cannot contain static data members unless it is static final;

③ inner classes can inherit classes that contain static members.


3. Anonymous inner class

Anonymous inner class, looks very strange. Because it's too concise, but it also brings a benefit, the code written in anonymous inner class is usually more concise! See the following code (left):


4. Internal classes allow multiple non-interface types to be inherited

Analyzing the code on the left, you can see that this syntax is very strange. But it's easier to understand. At the heart of the syntax is the return new () {Anonymous class definition}, which is a subclass of Anonymouysbase and then is transformed upward into the Anonymouysbase class. In fact, the code on the left is the simplification of the right code, we can look at the comparison. So, anonymous inner classes can simplify the code. There is also a need to note about anonymous inner classes:

① the parameters used by the anonymous inner class must be final;

② anonymous inner class because there is no name, it is impossible to have a constructor, only through the instance initialization to achieve the effect of a constructor.

As we all know, one of the differences between Java and C + + is that Java does not have multiple inheritance. At some point, however, we do need multiple inheritance, and the concept of "interface" is presented in Java. A class can implement multiple interfaces, which solves the problem of multiple inheritance? We think about it, but the interface only partially solves the problem of multiple inheritance. Each inner class can inherit from an interface or class independently, so no matter whether the peripheral class inherits an interface or class, it has no effect on the inner class. So the internal classes and interfaces are two swords, giving a perfect alternative to multiple inheritance in Java. See the following code:

Class D {}abstract class E {}class Z extends D {  E Makee () {return new E () {};}} public class Multiimplementation {  static void takesd (d d) {}  static void Takese (E-e) {} public  static void Ma In (string[] args) {    Z z = new Z ();    TAKESD (z);    Takese (Z.makee ());}  } ///:~

5. Internal class inheritance

Because the constructor of the inner class must be linked to a reference to the perimeter class object. So, when a class needs to inherit an inner class, that mysterious link to the external class must also be initialized. See Code:

Class Withinner {  class Inner {}}public class Inheritinner extends Withinner.inner {  //! Inheritinner () {}//Won ' t compile  inheritinner (Withinner wi) {    wi.super ();  }  public static void Main (string[] args) {    Withinner wi = new Withinner ();    Inheritinner II = new Inheritinner (WI);}  }

As shown in the code above, Inheritinner inherits the inner class, in order to enable the mysterious reference to the outer class to be initialized, the reference to the outer class needs to be passed as a parameter into the constructor of the inner class, and the super () function of the outer class is substituted in the constructor of the inner class.

6. Internal classes cannot be overwritten

There is a perimeter class that contains an inner class. When there is another class to inherit this outer class, and to overwrite this inner class. Can you really cover it? See the following code:

Class Egg {  private yolk y;  Protected class Yolk {public    yolk () {System.out.println ("egg.yolk ()");}  }  Public Egg () {System.out.println ("New Egg ()");    y = new yolk ();  }} public class Bigegg extends Egg {public  class yolk {public    yolk () {System.out.println ("bigegg.yolk ()");}  } public  static void Main (string[] args) {    new Bigegg ();  }}/* Output:new Egg () egg.yolk () *///:~

As can be seen from the output of the program, the inner class yolk in egg and its derived class Bigegg are actually independent and distributed in different spaces.

7. Internal classes vs nested classes

Nested classes in Java refer to the declaration of an inner class as static, then the inner class becomes a nested class. As a result, the two notable differences in nested classes, relative to the inner classes, are:

To create an object of a nested class, the object of its outer class is not required, so the mysterious reference to the outer class in the inner class disappears in the nested class;

A non-static member of its perimeter class cannot be accessed from the object of the nested class;

The nested class can include static members or methods.

Nested classes in Java and nested classes in C + + are actually a bit different. A nested class in C + + cannot access a private member of a perimeter class, but a nested class in Java can access a private member of static in its enclosing class. See Code:

Class Outterclass {Static class Anotherlevel {public   static void F () {System.out.println ("Test");}}} public class MainClass {public static void main (string[] args) {outterclass.anotherlevel.f ();}}///:~


8. Why to use Inner class?

After introducing the inner classes in Java, let's go back and summarize why we use internal classes. Landlord can only rely on the landlord

To summarize the understanding:

The ① inner class provides a green channel into its outer class;

? ② in general, the inner class inherits from a class or implements an interface, and the interface implements multiple inheritance in Java;

③private internal classes provide a way for designers of classes to completely block any type-dependent encoding and completely hide the implementation details;

④? Anonymous inner classes can make code more flexible.

Iv. PostScript
As for the inner classes in Java, let's start with the introduction of so many. In order to avoid the article too long, but also just picked a point to comb, some of the details of the things are not how to say. If there are deficiencies, please criticize, thank you.






















Why use internal classes in Java

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.