Using Inner class in Java

Categories: Java; Tagged with: ; @ May 22nd, 2012 1:03

Here is the code:

package innerClasds.scjp.liguoliang.com;

import java.io.Serializable;

public class TestInnerClass {
	
	private String name = "var+TestName";
	
	public static void main(String[] args) {
		new TestInnerClass().new InnerClass().printDes();
		new TestInnerClass().testInnerClassInMethod("info");
		TestInnerClass.StaticClass.printInfo();
	}

	/**
	 * 2. Inner class in method.
	 */
	void testInnerClassInMethod(final String info) {
		// In this class, we can get any variable in the outer class, but only can access the final variables in the method.
		// The reason is(from scjp book): can not keep variables(stored in stack) can keep as long as  inner class instance (stored in the heap),
		// so the inner class only access the final variable. 
		
		// and the class access modifier:  only abstract or final is permitted
		abstract class InnerClassInMethod {
			abstract void printInfo();
		}
		
		/** 3. Anonymous class;  */
		InnerClassInMethod inMethod = new InnerClassInMethod() {
			void printInfo() {
				System.out.println(InnerClassInMethod.class + TestInnerClass.this.name + "__" + info);
			}
		};
		
		inMethod.printInfo();
	}
	
	
	/**
	 * 1. Normal inner class. can use public, protected, (default), private accessor modifier to control the scope of the class.
	 * @author Li Guoliang
	 *
	 */
	private class InnerClass extends TestInnerClass implements Serializable{
		private static final long serialVersionUID = 1L;
		//always need final, otherwise: 
		//  The field s cannot be declared static; static fields can only be declared in static or top level types
		public static final String s = "s"; 
		void printDes() {
			System.out.println("Inner" + s + " " + TestInnerClass.class);
		}
	}
	
	/**
	 * 4. Static nested class.
	 * @author Li Guoliang
	 *
	 */
	private static class StaticClass {
		static void printInfo() {
			System.out.println(StaticClass.class);
		}
	}

}

Some comments:

1. Inner Class:

can be public, protected, private, final, abstract, static, strictfp.
need an outer instance to crate the inner instance, like: new TestInnerClass().new InnerClass();
Use outClass.this to get the outer instance;

2. Inner class in method

can be public, protected, private, final, abstract, static, strictfp;
can access any property in the outer instance;
only can access final variable in the method.

3. Anonymous class

4. Static nested class
can be public, protected, private, final, abstract, static, strictfp.

here are some notes when I first learn inner class in java: >>go<<

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.