Welcome 微信登录

首页 / 软件开发 / JAVA / 探讨Java内部类的可见性

探讨Java内部类的可见性2011-02-12zhangjunhd在Java中,当生成一个内部类的对象时,此对象与制造它的外部类通过外部类的.this保持着联系,因此该内部类对象可以访问其外部类对象的所有成员,包括private成员。

而该内部类对象对于其他类的对象的访问,遵照常规的访问权限语法,这一点也没有什么特别支持。这里需要探讨的是,外部类以及其他类的对象可以如何访问到某个内部类对象,即内部类的可见性问题。

下面是一个示例程序Out.java,其中包含了4个不同访问权限的内部类(private,default,protected,public),在每个内部类中,分别包含4个不同访问权限的成员与方法。在外部类Out中提供了得到内部类实例的方法。

Out.java

package com.zj.main;
public class Out {
public PrivateIn getPrivateIn(){
return new PrivateIn();
}

public DefaultIn getDefaultIn(){
return new DefaultIn();
}

public ProtectedIn getProtectedIn(){
return new ProtectedIn();
}

public PublicIn getPublicIn(){
return new PublicIn();
}

private class PrivateIn implements InMethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;

private void private_method(){};
void default_method(){};
protected void protected_method(){};
public void public_method(){};
}

class DefaultIn implements InMethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;

private void private_method(){};
void default_method(){};
protected void protected_method(){};
public void public_method(){};
}

protected class ProtectedIn implements InMethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;

private void private_method(){};
void default_method(){};
protected void protected_method(){};
public void public_method(){};
}

public class PublicIn implements InMethod{
private int private_arg;
int default_arg;
protected int protected_arg;
public int public_arg;

private void private_method(){};
void default_method(){};
protected void protected_method(){};
public void public_method(){};
}
public static void main(String[] args){
//create an outer object
Out out=new Out();

//create a private inner object by "new"
Out.PrivateIn privateIn=out.new PrivateIn();
privateIn.private_arg=0;
privateIn.private_method();

// create a private inner object by "out"s method"
Out.PrivateIn privateIn2 = out.getPrivateIn();
privateIn2.private_arg = 0;
privateIn2.private_method();
}
}