Home>

Java inner classes and their instantiations

In java, it is allowed to define another class inside one class (or method, statement block),It is called an inner class, sometimes called a nested class.

There is a logical belonging relationship between the inner class and the outer class that encapsulates it.Generally only used within the class or statement block in which it is defined,Implement some functional logic without universal meaning,You must give the full name when referring to it externally.

The main reasons for using inner classes are:

The inner class can access the data in the outer class,Including private data.

Inner classes can be hidden from other classes in the same package.

When i want to define a callback function and don't want to write a lot of code,It is more convenient to use anonymous inner classes.

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);
    system.out.println (inner.counter);
    //Compile Error,External class cannot access variables of inner class
    system.out.println (counter);
  }
}

This code defines an outer class outer, which contains an inner class inner. Comment out the error statement,Compiling produces two .class files:outer.class and outer $inner.class. That is,The inner classes are compiled into separate bytecode files.

Inner classes are a compiler phenomenon,It has nothing to do with virtual machines.The compiler will translate the inner class into a regular class file that separates the outer class name from the inner class name with a $sign,Virtual machines know 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 member variables in the outer class,Member variables must be instantiated to make sense.

Inner classes are new in java 1.1.Some programmers consider this a laudable advance,But the syntax of inner classes is complicated,Badly damaged good code structure, Violates the design philosophy that java is simpler than c++.

The inner classes seem to have increased—some nice and interesting,It ’s really unnecessary.Does this also make Java begin to embark on the destructive path of many languages ​​tortured?This tutorial is not intended to give a positive answer to this question.

Java static inner class, anonymous inner class, member inner class and local inner class

The inner class can be static and can use public, protected, and private access control characters.External classes can only use public or default.

Member inner class

A class that is defined directly inside an external class (not inside a method or inside a code block) is a member inner class,It can directly use all the variables and methods of the external class,Even private. If the outer class wants to access the member variables and methods of the inner class,You need to get through the object of the inner class.

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 inner class is like a regular member of the outer class.

Member inner classes can use various modifiers,It includes public, protected, private, static, final, and abstract, and it is optional.

If there is a static modifier, it is class-level,Otherwise it is object level.Class level can be accessed directly through external classes,The object level needs to generate external objects before it can be accessed.

You cannot declare any static members in a non-static inner class.

Inner classes can call each other,E.g:

class a {
  //b and c can call each other
  class b {}
  class c {}
}

Access to member inner classes

The object of the inner class records the reference of the outer class object that it depends on as a member variable.You can then find the outer class object and access its members.This member variable is automatically added for non-static inner classes.The name convention is "outclassname.this".

1) When using non-static variables and methods defined in the inner class,To create an object of the outer class,The object of the inner class is created by the "outobjectname.new" operator,Then call the methods 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. There is no dependency between its objects and the objects of the outer class.So it can be created directly.Examples are:

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);
    }
  }
}

operation result:

size=1

3) Since the inner class can directly access the components of its outer class,So when a property or method with the same name exists in the inner class and its outer class,It will also cause naming conflicts.Therefore, it must be specified in multiple calls,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 of inner class
      outer.this.size ++;//size of outer class
    }
  }
}

Local inner class

A local inner class is a class defined in a code block.They are only visible in the code block in which they are defined.

Local classes have several important characteristics:

Visible only in the code block in which they are defined; You can use any local final variables in the code block in which they are defined; Local classes cannot be static, and static members cannot be defined in them; Local classes cannot be modified with public, private, protected, only the default ones can be used;

Local classes can be abstract.

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=15;
    string str="http://www.weixueyuan.net";
    class inner {
      public void innertest () {
        system.out.println (total_number);
        system.out.println (id);
        //system.out.println (str);illegal, only final variables of local methods can be accessed
        system.out.println (age);
      }
    }
    new inner (). innertest ();
  }
  public static void main (string [] args) {
    outer outer=new outer ();
    outer.func ();
  }
}

operation result:

5
123
15

Anonymous inner class

Anonymous inner classes are a special form of local inner classes.That is, no variable name points to an instance of this class,And the concrete class implementation will be written in this inner class.

Note:Anonymous classes must inherit a parent class or implement an interface.

Implementing abstract methods without using anonymous inner classes:

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 ();
  }
}

operation result:

eat something

can be seen,We use child to inherit the person class and then implement an instance of child.Cast it upwards to a reference to the person class.However, if the child class is used only once,Wouldn't it be cumbersome to write it as a separate class?

At this time, anonymous inner classes were introduced.Implemented using anonymous inner classes:

abstract class person {
  public abstract void eat ();
}
public class demo {
  public static void main (string [] args) {
    //inherit the person class
    new person () {
      public void eat () {
        system.out.println ("eat something");
      }
    } .eat ();
  }
}

can be seen,The anonymous class inherits the person class and implements the methods of the abstract class in braces.

The syntax of inner classes is more complicated,It is also rarely used in actual development.This tutorial is not intended to be an in-depth explanation.Readers should not take inner classes as the focus of learning java.

  • Previous How to configure SQLSERVER ODBC under Linux
  • Next Simple understanding of the use of exception handling in Java programming