5. Internal class

Inner classes

E.g:

    class A {                   //外部类
        class B {  }            //内部类
}

After the above class compiler generates two separate categories: A.class A $ B.class
inner class can access private members of the outer class

Focus on inner classes:
  1. Internal class members: there is a class in which a class, for example, the above example
    to create an internal class object: to create external object, then creates internal class object (A a = new A () ; AB b = a.new B () ;)

  2. Static inner classes: an inner class is static modifier
    can create inner class object directly ① ② can only access static member outside the class: Features
    to create an internal class object: AB b = new AB () ;
  3. Local inner class: the definition of a class in which members of the method outside the class
    scope: starting with the definition, to where the code block end
    features: ① to create the object statement written in the method, the creation of local inner class ② local when you call a method outside of class inner class can access not only the members of the outer class, but also to access the local variables of the outer class, but it must be coupled with final (constant), (1.8 or more can not write, plus default virtual machine based on the code)
main:A a = new A(); 
a.method();  //注意,应将局部类的创建在方法内
class A { 
public void method() {
    class B {   }
}
}
  1. Anonymous inner classes: is a special type of internal
    conditions: ① implement an interface or inherit ② only when you create an object of this class when a class
    such as: to achieve the main function in one interface IA:
IA a = new IA(){     //直接实现该几口,没有要实现该接口的类名
        @Override
        public void method() { }//实现该接口的方法

Guess you like

Origin www.cnblogs.com/linanana/p/12075387.html