"Java basics of" Java inner class and instantiate

In Java, allow a class (or method, statement blocks) defined inside another class, called the class inner (Inner Class), sometimes referred to as a nested class (Nested Class).

Inner and outer package exists between the classes whose class belongs to a logical relationship, generally used in the definition of its class or block of statements, the logic does not implement some of the features of the generic sense, it must be given when the external reference complete it The name.

Inner classes are mainly used:
internal class can access the data in the external class, including private data.
Inner class can be hidden to other classes of the same package.
When you want to define a callback function and do not want to write a lot of code, use the anonymous (anonymous) more convenient inner class.
Reduce class naming conflicts.

Consider the following example:

public class Outer {
    private int size;
    public class Inner {
        private int counter = 10;
        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);
        The System. OUT.println (inner.counter);
         // compile error, can not access the internal variable outer class class
         // System.out.println (counter); 
    } 
}

operation result:

This code defines an external class Outer, comprising an inner class Inner. Comment out the wrong statement, the compiler will generate two .class files: Outer.class and Outer $ Inner.class. In other words, inner classes are compiled into independent bytecode files.

Internal compiler class is a phenomenon, regardless of the virtual machine. The compiler will translate into the inner classes separated by conventional external class file and class name inside the class name with the $ sign, while the virtual machine is not know anything about.

Note: You must have an object outside the class in order to generate the object within the class, because the internal class member variables need to access external class, member variables must be instantiated makes sense.

Inner classes are Java 1.1 new features, some programmers think this is a laudable progress, but the syntax is very complex inner class, severely damaged a good code structure, contrary to Java than C ++ simpler design.

It appears to increase the internal class - some interesting and beautiful, it is not necessary characteristic


Reference: https: //www.jianshu.com/p/2fcee8077169



Guess you like

Origin www.cnblogs.com/jssj/p/11391681.html