Java Inner class nesting class

Source: Internet
Author: User
Tags int size

Overview

Java allows us to define a class A in another Class B, then this class A is called an inner class. such as the following:

    • If the interior is similar to non-static, it is called an inner class
      class OuterClass { ... class NestedClass { ... } }

    • If the inner class is static then it is called a nested class or an internal static class
      ```
      Class Outerclass {
      ...
      Static Class Staticnestedclass {
      ...
      }

}
```

How to use common internal classes

Outer o = new Outer(); Outer.Inner i = o.new Inner();

    • An object of an inner class can be created only if it is associated with its external class.
    • When an inner class accesses an instance of an external class, you can use Outer.this to create an instance of the inner class using an instance object of the outer class. New Inner ()
    • An inner class object implicitly holds a reference to an external class object, and each instance of a non-static inner class is linked to an instance of an external class

      Static nested classes
  Outer.Inner i = new Outer.Inner();
    • If you do not need a connection between the inner class and its external class object, you can declare the inner class as static.
    • Cannot access non-static perimeter members

      Attention
    • If a class is to be declared static, there is only one case, the static inner class.
    • Static inner classes, like static methods, can access only static member variables and methods, cannot access non-static methods and properties, but ordinary inner classes can access member variables and methods of any external class
    • Static inner classes can declare ordinary member variables and methods, as well as static member variables and methods, while ordinary inner classes cannot declare static member variables and methods.

      Why you need a usage scenario for inner class internal classes

      Let's look at an example:

      First define an abstract class "
      /**
    • Selector iterators
      */
      Public abstract class Selector

```
/**

    • Wraps an integer array with the class and implements the addition by inheriting selector iterate through the iteration
      */
      public class Sequence extends Selector

      public Sequence (int size) {
      Items=new Object[size];
      }
      public void Add (int x) {
      if (next <items.length) {
      Items[next]=x;
      next++;
      }
      }

      /************************************ implementation abstract class */

      private int index=0;
      @Override
      Boolean Hasnext () {
      Return! (Index==items.length);
      }

      @Override
      Integer Next () {
      Integer Value=null;
      if (Hasnext ()) {
      Value=integer.parseint (Items[index].tostring ());
      index++;
      }
      return value;

      }
      }

我们定义一个Sequence类来包装了一个Object的数组,里面封装了添加初始化操作,通过继承了Selector<T> 来实现了迭代遍历功能。 这时如果我们需要Sequence再继承其他类怎么办?比如现在有一个类SequenceBiz
/**

    • sequence business required to inherit
      */
      public class Sequencebiz {
      public void log ()
      {
      //dosomestring Some businesses that require sequence inheritance
      System.out.println (This.getclass (). GetName () + "I recorded the Log");
      }
      }
      This time you can use an inner class to resolve ##### using an inner class
      /**
    • Wrapping an array of objects with classes and iterating through the inheritance selector using an inner class
    • Inherit sequencebiz to handle other business
      */
      public class Sequence1 extends sequencebiz{
      Private Object [] items;
      private int next =0;

      Public Sequence1 (int size) {
      Items=new object[size];
      }
      public void Add (int x) {
      if (next <items.length) {
      items[next]=x;
      next++;
      }
      }
      Private class Sequenceselector extends Selector

        @Overridepublic Integer Next () {integer VA    Lue=null;        if (Hasnext ()) {Value=integer.parseint (items[index].tostring ());    index++; } return value;}  
      }
      /**
      • return iterator
      • @return
        */
        Public Selector getselector ()
        {
        return new Sequenceselector ();
        }

}

我们来测试一下
public class Testinnerclass {
public static void Main (string[] args)
{
Sequence sequence=new Sequence (5);
for (int i=0;i<5;i++) {
Sequence.add (i);
// }
while (Sequence.hasnext ()) {
System.out.println (Sequence.next ());
// }
Sequence1 sequence1=new Sequence1 (5);
for (int i=0;i<5;i++) {
Sequence1.add (i);
}
Selector Selector=sequence1.getselector ();
while (Selector.hasnext ()) {
System.out.println (Selector.next ());
}
Sequence1.log ();
}
}

  ##### We look at the benefits of an inner class:-Using an inner class solves a problem in Java that cannot inherit multiple classes-Sequence1 creates a private inner class to implement selector hides the concrete implementation of selector. (This is the way of ArrayList iterators in the JDK source code)-Nesting small classes will make the codes closer to where they are used, making the code more maintainable, # # # # Static inner class scenes ##### create a static class ' public class Outer {pri      vate String name;        private int age;          public static class Builder {private String name;            private int age;          Public Builder (int.) {this.age = age;              Public Builder withname (String name) {this.name = name;          return this;              Public Builder Withage (int.) {this.age = age;          return this;          Public Outer Build () {Return to New Outer (this);          }} private Outer (Builder b) {this.age = B.age;      THIS.name = B.name; }  }  

The static inner class calls the constructor of the outer class to construct the outer class, since the static inner class can be initialized by itself and the following implementations are available externally. Builder design Pattern
We can use it in main
调用 Outer outer = new Outer.Builder(2).withName("Yang Liu").build();

Internal classes in the interface

The inner class that we define in the interface can only be a static inner class. Refer to the subject interface in the Shiro framework for usage scenarios.

/***生成器设计模式实现用于以简化的方式创建实例Builder design pattern implementation for creating {@link Subject} instances in a simplified way without requiring knowledge of Shiro‘s construction techniques.*/public interface Subject {     public static class Builder {              }}

You can refer to this design pattern for
-Https://www.cnblogs.com/zhuyuliang/p/5212746.html
-Builder Design Pattern

Description
Summarize
    • Using inner classes to resolve multiple inheritance issues
    • It is convenient to organize the classes with certain logical relationships and to hide them from the outside world.
    • Get code closer to where it's used, making your code more maintainable

      Reference
    • Https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
    • Https://www.cnblogs.com/chenssy/p/3388487.html
    • Https://www.cnblogs.com/dolphin0520/p/3811445.html
    • http://blog.csdn.net/hivon/article/details/606312

      The source address in the blog

      GitHub Address: Https://github.com/yalunwang/java-clump

Java Inner class nesting class

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.