Java private和protected修飾的內部類調用方法

Parcel2.java

abstract class Contents{
	abstract public int value();
}

interface Destination{
	String readLabel();
}

public class Parcel2 {
	private class PContents extends Contents{
		private int i = 11;
		public int value(){
			return i;
		}
	}
	
	protected class PDestination implements Destination{
		private String label;
		private PDestination(String whereTo){
			label = whereTo;
		}
		public String readLabel(){
			return label;
		}
	}
	
	public Contents cont(){
		return new PContents();
	}
	
	public Destination dest(String la){
		return  new PDestination(la);
	}
	/*
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Parcel2 p = new Parcel2();
		Contents c = p.cont();
		Destination d = p.dest("lalala");
		System.out.println(d.readLabel() + c.value());
	}
	*/
}

Test.java

public class Test {

	public static void main(String[] args){
		Parcel2 p = new Parcel2();
		Contents c = p.cont();
		Destination d = p.dest("lalala");
		System.out.println(d.readLabel() + c.value());
	}
}

運行結果:

Parcel2註釋裏面的代碼是可以成功運行的。

Test也是可以成功運行的。(通過public 方法調用private和protected類)。

普通類(非內部類)不可設爲private或protected,只允許是public或“友好的”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章