Details on the use of inner classes in Java
- 2020-04-01 01:42:29
- OfStack
Inner class access rules
The & # 8226; Inner classes have direct access to members in outer classes, including private ones. Access format: external class name. This
The & # 8226; An inner class object must be created for an outer class to access an inner class.
The & # 8226; The inner class is in the member position and can be modified by the member modifier.
public class InnerClassDemo1 {
public static void main(String[] args){
Outer ou =new Outer();
ou.method();// 4 3
Outer.Inner oi =new Outer().new Inner();
oi.function2();
}
}
class Outer{
private int x=3;
class Inner{
int x=4;
void function1(){
System.out.println(x);
System.out.println(Outer.this.x);
}
void function2(){
Outer.this.method();
}
}
public void method(){
Inner in =new Inner();
in.function1();
}
}
Static inner class
The & # 8226; Inner classes define static members, and inner classes must be static.
class InnerClassDemo2
{
public static void main(String[] args)
{
new Outer.Inner().function();//Create a static inner class object
}
}
class Outer
{
private static int x=5;
static class Inner//Static inner classes can only access static members of external classes
{
void function()
{
System.out.println("inner:"+x);
}
}
}
Local inner class
The & # 8226; When the inner class is defined locally, members in the outer class can be accessed directly.
The & # 8226; Access to local variables must be final modified.
class InnerClassDemo3
{
public static void main(String[] args)
{
Outer out =new Outer();
out.method(7);
}
}
class Outer
{
int x=3;
public void method(final int a)
{
class Inner
{
void function()
{
System.out.println(a);
}
}
new Inner().function();
}
}
Anonymous inner class
The & # 8226; Anonymous inner classes are shorthand for inner classes.
The & # 8226; The premise of anonymous inner classes: inner classes must inherit from a class or implement an interface.
The & # 8226; An anonymous inner class cannot create a constructor.
class InnerClassDemo4
{
public static void main(String[] args)
{
Demo d=new Demo()
{
void show()
{
System.out.println(" Anonymous inner class show methods ");
}
void method()
{
System.out.println(" Anonymous inner class method methods ");
}
}.show();
d.method();
}
}
abstract class Demo
{
abstract void show();
}