package demos.other.java;
/**
* <code>InnerClassDemo</code>
*
* @author zhuan.liu 17-7-23
* @version 1.0
*/
public class InnerClassDemo {
private String s1 = "s1";
public String s2 = "s2";
protected String s3 = "s3";
private static String s4 = "s4";
/**
* 静态内部类
*
* 1.使用时不依赖外部类;
* 2.可以任意访问外部类的static变量;
* 3.外部类可以直接访问static类型变量;
* 4.外部类需要构建实例才能访问非static变量;
*/
public static class StaticInnerClass {
private String staticInnerClassS1 = "sis1";
public String staticInnerClassS2 = "sis2";
protected String staticInnerClassS3 = "sis3";
public static String staticInnerClassS4 = "sis4";
public void execute() {
s4 = "4";
System.out.println("StaticInnerClass" + s4);
}
}
/**
* 成员内部类
*
* 1.使用时必须构建外部类实例;
* 2.可以任意访问外部类的所有变量;
* 3.外部类访问时须构建内部类的实例;
* 4.类成员中不能有static类型变量;
*/
public class InnerClass {
private String innerClassS1 = "is1";
public String innerClassS2 = "is2";
protected String innerClassS3 = "is3";
public void execute() {
s1 = "1";
s4 = "4";
System.out.println("InnerClass");
}
}
public void execute() {
final String s = "execute";
InnerClass innerClass = new InnerClass();
innerClass.innerClassS1 = "is1";
StaticInnerClass staticInnerClass = new StaticInnerClass();
staticInnerClass.execute();
StaticInnerClass.staticInnerClassS4 = "sis4";
/**
* 局部内部类
* 1.只在方法内部使用,类似于方法内的变量;
* 2.只能调用方法中的final变量;
* 3.可以任意访问外部类的所有变量;
*/
class InnerClassMethod {
public void execute() {
s2 = "2";
s4 = "4";
System.out.println("InnerClassMethod" + s);
}
}
new InnerClassMethod().execute();
}
public static void main(String[] args) {
try {
InnerClassDemo innerClassDemo = new InnerClassDemo();
StaticInnerClass staticInnerClass = new StaticInnerClass();
staticInnerClass.execute();
InnerClassDemo.InnerClass innerClass = new InnerClassDemo().new InnerClass();
innerClass.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JAVA内部类
最新推荐文章于 2024-04-25 12:25:03 发布