Java private和protected修饰的内部类调用方法

版权声明:本文为博主原创文章,转载请注明原博客地址。 https://blog.csdn.net/u012210441/article/details/51926456

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或“友好的”。

猜你喜欢

转载自blog.csdn.net/u012210441/article/details/51926456