A comprehensive interpretation of inner class _java in Java programming

Source: Internet
Author: User
Tags control characters int size static class

Java internal classes and their instantiation
In Java, it is allowed to define another class within a class (or method, statement block), called an inner class (Inner Class), sometimes called a nested class (Nested Class).

There is a logical affiliation between the inner class and the outer wrapper of its class, which is generally used only within the class or statement block in which it is defined, to implement functional logic that does not have universal meaning, and must give a complete name when it is referenced externally.

The main reasons for using internal classes are:
An inner class can access data in an external class, including private data.
An inner class can be hidden from other classes in the same package.
When you want to define a callback function and do not want to write a large amount of code, it is convenient to use an anonymous (anonymous) inner class.
Reduce naming conflicts for classes.

Take a look at the following example:

public class Outer {
  private int size;
  public class Inner {
    private int counter = ten;
    public void Dostuff () {
      size++
    }}
  public static void Main (String args[]) {
    Outer Outer = new Outer ();
    Inner Inner = Outer.new Inner ();
    Inner.dostuff ();
    System.out.println (outer.size);
    System.out.println (inner.counter);
    Compilation error, external class cannot access variable
    System.out.println (counter) of inner class;
  }

This code defines an external class Outer, which contains an internal class Inner. Comment out the error statement, compile, and generate two. class files: Outer.class and Outer$inner.class. In other words, the inner class is compiled into a separate byte-code file.

An inner class is a compiler phenomenon that has nothing to do with virtual machines. The compiler will translate the inner class into a regular class file that separates the external class name from the internal class name with the $ symbol, and the virtual machine knows nothing about it.

Note: You must have an object of the outer class before you can generate an object of the inner class, because the inner class needs to access the member variables in the external class, and the member variables must be instantiated to make sense.

The inner class is a new feature of Java 1.1, some programmers think this is a commendable progress, but the internal class syntax is very complex, seriously damaging the good code structure, against Java is more simple than C + + design concept.

Does the inner class seem to have increased-something beautiful, interesting, unnecessary, and does that make Java embark on a devastating path that many languages suffer? This tutorial is not intended to give a positive answer to this question.

Java static internal classes, anonymous inner classes, member-internal classes, and local inner classes
An inner class can be static (static), can use public, protected, and private access control characters, and an external class can only use public, or default.
member Inner class

A class that is directly defined within an external class (not within a method or inside a code block) is a member-internal class that can directly use all the variables and methods of an external class, even if it is private. To access the member variables and methods of an inner class, an external class needs to be acquired by an object of the inner class.

Take a look at the following code:

public class outer{
  private int size;
  public class Inner {public
    void Dostuff () {
      size++;
    }
  }
  public void Testtheinner () {
    Inner in = new Inner ();
    In.dostuff ();
  }

A member-internal class is like an ordinary member of an external class.

Member-Inner classes can use various modifiers, including public, protected, private, static, final, and abstract, or not.

If there is a static modifier, it is a class level, otherwise it is an object level. Class-level can be accessed directly from an external class, and object-level needs to be external to the object.

No static member can be declared in a non-static inner class.

Inner classes can be invoked with each other, for example:

Class A {
  //b, C can call each other
  class B {}
  class C {}
}


access to member-type inner classes

An object of an inner class records the reference of the outer class object that it relies on as a member variable, so that the outer class object can be found and accessed by its members. The member variable is automatically added by the system to a non static inner class, and the name convention is "Outclassname.this".

1 when using the Non-static variables and methods defined in the inner class, you first create an object of the outer class, then create an object of the inner class by the "Outobjectname.new" operator, and then call the method of the inner class, as follows:

public class demo{public
  static void Main (string[] args) {
    Outer Outer = new Outer ();
    Outer.Inner Inner = Outer.new Inner ();
    Inner.dostuff ();
  }
Class outer{
  private int size;
  Class inner{public
    void Dostuff () {
      size++
    }
}}

2 The static inner class is equivalent to the static member of its outer class, and its object does not have a dependency relationship with the external class object, so it can be created directly. Examples are as follows:

public class demo{public
  static void Main (string[] args) {
    Outer.Inner Inner = new Outer.Inner ();
    Inner.dostuff ();
  }
Class outer{
  private static int size;
  Static class Inner {public
    void Dostuff () {
      size++;
      System.out.println ("size=" + size);}}

Run Result:

Size=1

3 because an inner class can directly access the composition of its outer class, it also causes a naming conflict when an intrinsic class has a property or method of the same name in its outer class. So when you call on multiple layers, you want to indicate, as follows:

public class outer{
  private int size;
  public class inner{
    private int size;
    public void Dostuff (int size) {
      size++;//local variable size;
      This.size; Size outer.this.size++ of inner class
      ;//outer class size
    }}

Local inner class

A local inner class, which is a class that is defined in a code block. They are visible only in the block of code that defines them.

The local class has several important features:

    • is visible only in blocks of code that define them;
    • You can use any local final variable in the code block that defines them;
    • The local class cannot be static, nor can the static member be defined inside.
    • The local class cannot be decorated with public, private, protected, and can only use the default;

The local class can be abstract.

Take a look at the following code:

public class Outer {public
  static final int total_number = 5;
  public int id = 123;
  public void Func () {
    final int age =;
    String str = "http://www.weixueyuan.net";
    Class Inner {public
      void Innertest () {
        System.out.println (total_number);
        SYSTEM.OUT.PRINTLN (ID);
        System.out.println (str); is not appropriate to access the final variable
        System.out.println (age)
    of the local method; New Inner (). Innertest ();
  }
  public static void Main (string[] args) {
    Outer Outer = new Outer ();
    Outer.func ();
  }

Run Result:

5
123
15


Anonymous Inner class

An anonymous inner class is a special form of a local inner class, where no variable name points to an instance of the class, and the concrete class implementation is written in the inner class.

Note: An anonymous class must inherit a parent class or implement an interface.

Do not use anonymous inner classes to implement abstract methods:

Abstract class Person {public
  abstract void Eat ();
}
Class Child extends person {public
  void Eat () {
    System.out.println ("Eat something");
  }
public class Demo {public
  static void Main (string[] args) {person
    p = new Child ();
    P.eat ();
  }

Run Result:

Eat something

As you can see, we inherited the person class with a child and then implemented an instance of the child, transforming it upward into a reference to the person class. However, if the child class here is used only once, would it be troublesome to write it as a separate class?

This time the anonymous inner class is introduced. Implemented using anonymous inner classes:

Abstract class Person {public
  abstract void Eat ();
}
public class Demo {public
  static void Main (string[] args) {
    
    //Inherit person class
    new person () {public
      void Eat () {
        System.out.println ("Eat something");
      }
    . Eat ();
  }


As you can see, the anonymous class inherits the person class and implements the abstract class method in curly braces.

The syntax of the

Inner class is more complex and less used in actual development, this tutorial is not intended for in-depth explanation, and readers should not use the inner class as the focus of learning 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.