Inner classes, anonymous classes

1. What is the inner class?
"JAVA programming" in this definition:
internal class (also known as embedded type), is defined inside one of the other classes. Here are examples:

public class showInnerClass{
  private int date;
public void m(){
 InnerClass instance = new InnerClass();
 }
class InnerClass{
public void mi(){
data++;
m();
  }
 }
}

InnerClass class defined inside showInnerClass class. Has the following characteristics:
(1) internal class reference contains data and methods in its outer class, it is not necessary to reference external class passed to the constructor within the class, for this reason, the internal class can make the program simple.
(2) for supporting a work only inside the outer class class. After compiling his name like "external class name Inside unit class name Call . c l a s s Case Such as s h O w I n n e r C l a s s in Inside unit class I n n e r C l a s s , Is Edit Translate for s h O w I n n e r C l a s s Internal .class class name. "For example, showInnerClass inner class InnerClass, is compiled into showInnerClass $ InnerClass.class.
(3) internal class can be declared as public, protected, private, its meaning is the same with the other members of the class.
(4) internal class can be declared as static, you can use the class name of the outer class to access static inner classes, static inner classes but can not access non-static member outside the class.
(5) often create objects within the class outside the class, but can also be created inside the object class from another class. If a non-static inner class, you must first create an instance of the outer class, and then create objects within the class uses the following syntax:

External Internal class class class internal object name = .new internal external object class ();

(6) If the inner class is static, you can create it using the following syntax object:

External classes within a class name = new class object inside the outer class inner class ();

2. Why do we need inner classes?
Some people have a problem: something to be achieved inside the class with something previously learned can also be achieved, why use it? This problem can be explained in terms of coarse it from the environment. In some places we use methods within the class would be more convenient.

3. anonymous class
anonymous class is a subclass of no name. Because there is no name, it can make the code more concise. . E.g.
Bank a class object with the following code creates a subclass of Bank:

new Bnak(){
...类体
}

We can see that this makes creating subclasses of objects more concise. But there is also a limitation, is the first use. You can not use this second category, because no name.

Published 35 original articles · won praise 0 · Views 1299

Guess you like

Origin blog.csdn.net/c1776167012/article/details/102942213