java编程思想笔记(七)内部类

1.内部类的定义:

将一个类的定义放到另一个类内部中,即为内部类。内部类可调用外围类的成员变量和方法,

像这种直接在外围类中定义的内部类,叫成员内部类,这种内部类可使用到外围类全部的成员变量和方法.

 

内部类也能保证抽象类或具体类实现多重继承的功能。(如用多个不同内部类去继承多个不同具体类)

 

内部类就像是一个怀孕的妈妈肚子里的孩子,孩子可以吸收到母亲的养分,又能有自己成员信息.

 

2.在外部类的非静态方法中创建内部类的对象语法:

外部类类名.内部类类名 对象名 = 外部类对象.new 内部类类名();

 

3.this. 或  new

内部类使用 外围类.this,可引用外围类对象,外围类可以通过new得到内部类对象,外围类之外是做不到的.

 

public class Outter{  
    void f(){  
System.out.println(“Outter f() method”);  
}  
    class Inner{  
    public Outter outer(){  
        return Outter.this;  
}  
}  
    public Inner inner(){  
        return new Inner();  
}  
} 

 

 

4.内部类实现接口后的向上转型.

 

 

 

interface Contents {
	int value();
}  

public interface Destination {
	String readLabel();
}  

class outer{
	private class PContents implements Contents {
		private int i = 11;

		public int value() {
			System.out.println("PContents value");
			return i;
		}
	}

	protected class PDestination implements Destination {
		private String label;

		private PDestination(String whereTo) {
			label = whereTo;
		}

		public String readLabel() {
			System.out.println(label);
			return label;
		}
	}

	public Destination destination(String s) {
		return new PDestination(s);
	}

	public Contents contents() {
		return new PContents();
	}
}
public class TestOuter {
	public static void main(String[] args) {
		Outer p = new Outer();
                Contents c = p.contents();
		Destination d = p.destination("Tasmania");
		c.value();
		d.readLabel();
		// Illegal -- can't access private class:
		// ! Outer.PContents pc = p.new PContents();
	}
} // /:~

 

5.在方法和作用域内的内部类

 

    定义在方法里的局部内部类:

 

public class Parcel5 {
	public Destination destination(String s) {
		//定义在方法里,为局部内部类
		class PDestination implements Destination {
			private String label;

			private PDestination(String whereTo) {
				label = whereTo;
			}

			public String readLabel() {
				return label;
			}
		}
		return new PDestination(s);
	}

	public static void main(String[] args) {
		Parcel5 p = new Parcel5();
		Destination d = p.destination("Tasmania");
	}
} // /:~

 

 

作用域里的内部类

 

public class Parcel6 {
	private void internalTracking(boolean b) {

		if (b) {
			// 定义在if作用域内的内部类
			class TrackingSlip {
				private String id;

				TrackingSlip(String s) {
					id = s;
				}

				String getSlip() {
					return id;
				}
			}
			TrackingSlip ts = new TrackingSlip("slip");
			String s = ts.getSlip();

		}
		// 已经在作用域外部,内部类不能用于此:
		// ! TrackingSlip ts = new TrackingSlip("x");
	}

	public void track() {
		internalTracking(true);
	}

	public static void main(String[] args) {
		Parcel6 p = new Parcel6();
		p.track();
	}
} // /:~

 

 

6。匿名内部类

 

public class Parcel7 {
	public interface Contents {
		int value();
	} // /:~

	abstract class hhm {
		public int i = 5;

		public void ttt() {
		};
	}

	public Contents contents() {
		return new Contents() { // 这里直接new了Contents类,前提是要有个Contents名字的接口或类
			private int i = 11;

			public int value() {
				return i;
			}
		}; // *这里要分号
	}

	public hhm gethhm() {
		return new hhm() {

		};
	}

	public static void main(String[] args) {
		Parcel7 p = new Parcel7();
		Contents c = p.contents();
	}
} // /:~

 

 

 

如果匿名内部类的基类有个有参构造器,并且没有无参构造器.

那就直接参数传给匿名内部类,用super获取值.

 

public class Parcel8 {
	class Wrapping {
		private int i;

		public Wrapping(int x) {
			i = x;
		}

		public int value() {
			return i;
		}
	} // /:~

	public Wrapping wrapping(int x) {
		// Base constructor call:
		return new Wrapping(x) { // Pass constructor argument.
			public int value() {
				System.out.println(super.value());
				return super.value() * 47;
			}
		}; // Semicolon required
	}

	public static void main(String[] args) {
		Parcel8 p = new Parcel8();
		Wrapping w = p.wrapping(10);
		w.value();
	}
} // output : 10 /:~

 

为匿名内部类创建一个初始化构造器的效果:

 

abstract class Base {
	public Base(int i) {
		print("Base constructor, i = " + i);
	}

	public abstract void f();
}

public class AnonymousConstructor {
	public static Base getBase(int i) {
		return new Base(i) {
			{
				print("Inside instance initializer");
			}

			public void f() {
				print("In anonymous f()");
			}
		};
	}

	public static void main(String[] args) {
		Base base = getBase(47);
		base.f();
	}
} /*
 * Output: Base constructor, i = 47 Inside instance initializer In anonymous f()
 */// :~

 上面的方法参数i不需要加final修饰,因为i是传给了构造器

 若内部类想直接使用方法上的参数,那就用final修饰方法参数.

 

7.静态内部类

定义:内部类前面加static修饰即为静态内部类,也叫嵌套类。

1)静态内部类不需要外围类,即可创建静态内部类对象。

 2)不能从静态内部类对象中访问外围类的非静态内部类对象

 

public class Parcel11 {
	private int q = 5555;

	private static class ParcelContents implements Contents {
		private int i = 11;

		public int value() {
			// ! q++; //静态内部类中想调用外围类的参数q就必须用static修饰才能q++
			return i;
		}
	}

	static class ParcelDestination implements Destination {
		private String label;

		private ParcelDestination(String whereTo) {
			label = whereTo;
		}

		public String readLabel() {
			return label;
		}

		// Nested classes can contain other static elements:
		public static void f() {
		}

		static int x = 10;

		static class AnotherLevel {
			public static void f() {
				ParcelDestination.f();
			}

			static int x = 10;
		}
	}

	public static Destination destination(String s) {
		// 静态内部类不需通过外围类即可创建内部类
		return new ParcelDestination(s);
	}

	public static Contents contents() {
		return new ParcelContents();
	}

	public static void main(String[] args) {
		Contents c = contents();
		Destination d = destination("Tasmania");

	}
} // /:~
 

 8.闭包与回调

java中可以通过内部类实现闭包与回调

参考:

http://blog.csdn.net/yaerfeng/article/details/7326956

 

interface Incrementable {
	void increment();
}

// Very simple to just implement the interface:
class Callee1 implements Incrementable {
	private int i = 0;

	public void increment() {
		i++;
		System.out.println("Callee1 :" + i);
	}
}

class MyIncrement {
	public void increment() {
		print("Other operation");
	}

	static void f(MyIncrement mi) {
		mi.increment();
	}
}

// If your class must implement increment() in
// some other way, you must use an inner class:
class Callee2 extends MyIncrement {
	private int i = 0;

	public void increment() {
		super.increment();
		i++;
		System.out.println("Callee2 :" + i);
	}

	private class Closure implements Incrementable {
		public void increment() {
			// Specify outer-class method, otherwise
			// you'd get an infinite recursion:
			Callee2.this.increment();
		}
	}

	Incrementable getCallbackReference() {
		return new Closure();
	}
}

class Caller {
	private Incrementable callbackReference;

	Caller(Incrementable cbh) {
		callbackReference = cbh;
	}

	void go() {
		callbackReference.increment();
	}
}

public class Callbacks {
	public static void main(String[] args) {
		Callee1 c1 = new Callee1();
		Callee2 c2 = new Callee2();
		MyIncrement.f(c2);
		Caller caller1 = new Caller(c1);
		Caller caller2 = new Caller(c2.getCallbackReference());
		caller1.go();
		caller1.go();
		caller2.go();
		caller1.go();
		caller2.go();
	}
} /*
 * Output: Other operation 1 1 2 Other operation 2 Other operation 3
 */// :~
 

9.内部类的继承

   新类若想继承其它类中的内部类,必须先初始化其它类的构造器才用的到其中的内部类.

class WithInner {
	class Inner {
		
	}
}

public class InheritInner extends WithInner.Inner {
	// ! InheritInner() {} // 不能编译
	InheritInner(WithInner wi) {
		wi.super();
	}

	public static void main(String[] args) {
		WithInner wi = new WithInner();
		InheritInner ii = new InheritInner(wi);
	}
} // /:~

 

总结:

在代码块里创建内部类是使用局部内部类还是匿名内部类?

若需要一个已命名的构造器,或者需要重载构造器,或你需要更多内部类完成功能,就使用局部内部类.

若只需一个内部类作实例初始化,就用匿名内部类.

 

猜你喜欢

转载自201601175907.iteye.com/blog/2365055
今日推荐