Java语言基础:内部类
1. 普通内部类
普通内部类的一个最简单的例子:
view plaincopy to clipboardprint?
// 外部类
class OutterClass {
// 内部类
public class InnerClass {
private int i = 0;
public int getInt(){
return i;
}
}
public void proc(){
InnerClass inClass = new InnerClass();
System.out.println(inClass.getInt());
}
}
public class Main {
public static void main(String[] args) {
OutterClass outClass = new OutterClass();
outClass.proc();
}
}
// 外部类
class OutterClass {
// 内部类
public class InnerClass {
private int i = 0;
public int getInt(){
return i;
}
}
public void proc(){
InnerClass inClass = new InnerClass();
System.out.println(inClass.getInt());
}
}
public class Main {
public static void main(String[] args) {
OutterClass outClass = new OutterClass();
outClass.proc();
}
}
外部类可以访问内部类的私有成员,内部类也可以访问外部类的私有成员:
view plaincopy to clipboardprint?
// 外部类
class OutterClass {
private int mOut = 10;
// 内部类
public class InnerClass {
private int mIn = 0;
public void printOutPrivate(){
// 直接打印外部类的成员
System.out.println(mOut);
}
}
public void printInPrivate(){
InnerClass inClass = new InnerClass();
// 直接打印内部类的私有成员
System.out.println(inClass.mIn);
}
public void printOutPrivate(){
InnerClass inClass = new InnerClass();
inClass.printOutPrivate();
}
}
public class Main {
public static void main(String[] args) {
OutterClass outClass = new OutterClass();
outClass.printInPrivate();
outClass.printOutPrivate();
}
}
// 外部类
class OutterClass {
private int mOut = 10;
// 内部类
public class InnerClass {
private int mIn = 0;
public void printOutPrivate(){
// 直接打印外部类的成员
System.out.println(mOut);
}
}
public void printInPrivate(){
InnerClass inClass = new InnerClass();
// 直接打印内部类的私有成员
System.out.println(inClass.mIn);
}
public void printOutPrivate(){
InnerClass inClass = new InnerClass();
inClass.printOutPrivate();
}
}
public class Main {
public static void main(String[] args) {
OutterClass outClass = new OutterClass();
outClass.printInPrivate();
outClass.printOutPrivate();
}
}
如果外部类的成员变量与内部类的成员变量名字相同,当内部类要访问外部类的该成员时,可以使用“OutClass.this.mem”来区分:
view plaincopy to clipboardprint?
// 外部类
class OutterClass {
private int mMem = 10;
// 内部类
public class InnerClass {
private int mMem = 0;
public void printOutPrivate(){
// 直接打印外部类的成员
System.out.println(OutterClass.this.mMem);
}
}
}
// 外部类
class OutterClass {
private int mMem = 10;
// 内部类
public class InnerClass {
private int mMem = 0;
public void printOutPrivate(){
// 直接打印外部类的成员
System.out.println(OutterClass.this.mMem);
}
}
}
要创建普通内部类,必须先创建相应的外部类:
view plaincopy to clipboardprint?
// 外部类
class OutterClass {
private int mMem = 10;
// 内部类
public class InnerClass {
private int mMem = 0;
public void printOutPrivate(){
// 直接打印外部类的成员
System.out.println(OutterClass.this.mMem);
}
补充:软件开发 , Java ,