Java点滴: Nested Class

参考贴:内部类详解
tag: java,nested class

Why do we need it?

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

More scenario-sense

  • 内部类提供了某种进入外围类的窗户。
  • 每个内部类都能独立地继承一个接口,而无论外围类是否已经继承了某个接口。

因此,内部类使多重继承的解决方案变得更加完整。在项目中,需要多重继承,如果是两个接口,那么好办,接口支持多重继承。如果是两个类呢?这时只有使用内部类了。

Sample
public class NestedClassDemo {
	
	private int _value = 1;
	private static String _id = "1";	
	
	// 1. member class, defined in class
	//    inner class, scope: member
	private class InnerA {
		private int _value;
		public InnerA(int value) {
			_value = value;
		}
		public void readOuterA() {
			// accessing outer class' member directly
			System.out.println(_value);
		}		
		public void readOuterB() {
			// accessing outer class' member alternatively
			System.out.println(NestedClassDemo.this._value);
		}
	}
	
	public void foo() {
		// 2. local class, defined in method, compiled with method
		//    inner class, scope: local (stack)
		class InnerB {
			public void show() {
				System.out.println("NestedB defined in method");
			}
		}
		// must be called afterwards
		new InnerB().show();
	}
	
	public Object createAnonymous() {
		final String temp = "anonymous";
		// 3. anonymous inner class
		//    inner class, scope: point it is defined
		return new Object() {			
			private int _value;	
			private String _id;
			// initializer, using alternative way to resolve conflict
			{
				_value = NestedClassDemo.this._value;
				_id = temp; // can only refer to final local variable
			} 
			public String toString() {
				return _id + _value;
			}
		};
	}
	
	// 4. nested static class, behaviors like a top-level class
	//    non-inner class, scope: (static) member 
	private static class Nested {
		public void readOuter() {
			// can access only static fields
			System.out.println(_id);
		}
	}

	public static void main(String[] args) {
		
		NestedClassDemo nc = new NestedClassDemo();		
		// initialization: outerObj.new 
		NestedClassDemo.InnerA a = nc.new InnerA(nc._value);
		// InnerA a = nc.new InnerA(); // is acceptable here
		a.readOuterA();
		a.readOuterB();
		
		NestedClassDemo.Nested n = new NestedClassDemo.Nested();
		// Nested n = new Nested(); // is acceptable here		
		n.readOuter();
	}	
}

public interface Service {
	void serve();
}

public interface ServiceFactory {
	Service getService();
}

public class ServiceImpl implements Service {	
	public void serve() {
		// do something
	}
	public static ServiceFactory getService() {
		return new ServiceFactory() {			
			public Service getService() {
				return new ServiceImpl();
			}
		};
	}
}

你可能感兴趣的:(java,Access)