Java非静态内部类和静态内部类,访问父类的非静态和静态成员变量及成员函数

 public class Test { // Not static variable private int mAge = 10; // Static variable private static int mId = 1; // Single instance object private static Test test = null; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("--- main() start --->"); test = getIntance(); InnerClass ic; ic = test.new InnerClass(); System.out.println("----------------"); test.setAge(20); test.setId(2); InnerStaticClass isc; isc = new InnerStaticClass(); System.out.println("--- main() end <---"); } /** * Get single instance object */ public static Test getIntance() { if (null == test) { test = new Test(); } return test; } public int getAge() { return mAge; } public void setAge(int age) { mAge = age; } public static int getId() { return mId; } public static void setId(int id) { mId = id; } /** * Not static inner class */ public class InnerClass { private int mInnerAge; private int mInnerId; public InnerClass() { System.out.println("InnerClass"); mInnerAge = mAge; // OK mInnerAge = getAge(); // OK System.out.println("mInnerAge = " + mInnerAge); mInnerId = mId; // OK mInnerId = getId(); // OK System.out.println("mInnerId = " + mInnerId); } } /* * Static inner class */ public static class InnerStaticClass { private int mInnerAge; private int mInnerId; public InnerStaticClass() { System.out.println("InnerStaticClass"); // Cannot make a static reference to the non-static field mAge // mInnerAge = mAge; // Cannot make a static reference to the non-static method getAge() from the type Test // mInnerAge = getAge(); System.out.println("mInnerAge = " + mInnerAge); mInnerId = mId; // OK mInnerId = getId(); // OK System.out.println("mInnerId = " + mInnerId); } } }

输出:

--- main() start --->
InnerClass
mInnerAge = 10
mInnerId = 1
----------------
InnerStaticClass
mInnerAge = 0
mInnerId = 2
--- main() end <---

你可能感兴趣的:(java)