Java实例说明 嵌套类包括内部类(即非静态嵌套类)和静态嵌套类 两者的区别

来源:互联网 发布:php扩展开发.pdf 编辑:程序博客网 时间:2024/06/05 20:14

内部类实例代码:



public class OuterMyTest {


class InnerMyTest{

}
 
public static void main(String[] args) {

InnerMyTest innerMyTest = new InnerMyTest();
}


}


编译报错:No enclosing instance of type OuterMyTest is accessible. Must qualify the allocation with an enclosing instance of type OuterMyTest (e.g. x.new A() where x is an instance of OuterMyTest).


说明:内部类实例化需要先实例化外部类  x.new A() 


代码改进:

public class OuterMyTest {    // 定义外部类  

String s = "来访问外部类的属性吧!";    // 定义外部类的私有属性  


class InnerMyTest{  // 定义内部类  


public void getInnerMyTest(){   // 定义内部类的方法  
System.out.println(s);         // 直接访问外部类的私有属性  
}
}

public void fun(){        // 定义外部类的方法  
new InnerMyTest().getInnerMyTest();     // 通过内部类的实例化对象调用方法
}
 
public static void main(String[] args) {
OuterMyTest outerMyTest = new OuterMyTest();    // 外部类实例化对象  
InnerMyTest innerMyTest = outerMyTest.new InnerMyTest();   // 实例化内部类对象  
innerMyTest.getInnerMyTest();     // 调用内部类的方法  
outerMyTest.fun();           // 调用外部类的方法  
}


}

运行结果:

来访问外部类的属性吧!


说明:

OuterMyTest outerMyTest = new OuterMyTest();
InnerMyTest innerMyTest = outerMyTest.new InnerMyTest();


我们在执行代码InnerMyTest innerMyTest = outerMyTest.new InnerMyTest();的时候,其实做了两件事:

一件事是创建一个内部类的实例innerMyTest 

第二件事是让innerMyTest 绑定outerMyTest 作为其外围类的实例。这样innerMyTest 就可以访问outerMyTest 内的所有成员属性以及方法了。


静态嵌套类实例代码:


public class OuterMyTest {

String s = "来访问外部类的属性吧!";


static class InnerMyTest{


public void getInnerMyTest(){
System.out.println(s);
}
}

public void fun(){
new InnerMyTest().getInnerMyTest();
}
 
public static void main(String[] args) {
OuterMyTest outerMyTest = new OuterMyTest();
InnerMyTest innerMyTest = outerMyTest.new InnerMyTest();
innerMyTest.getInnerMyTest();
outerMyTest.fun();
}


}

编译报错: Illegal enclosing instance specification for type OuterMyTest.InnerMyTest

给静态嵌套类OuterMyTest .InnerMyTest 指定了非法的外围类的实例。


代码改进:

public class OuterMyTest {

static
String s = "来访问外部类的属性吧!";
static class InnerMyTest{
public void getInnerMyTest(){
System.out.println(s);  // s要设置为静态变量,否则编译报错:Cannot make a static reference to the non-static field s
}
}

public void fun(){
new InnerMyTest().getInnerMyTest();
}
 
public static void main(String[] args) {
OuterMyTest.InnerMyTest innerMyTest = new OuterMyTest.InnerMyTest();
innerMyTest.getInnerMyTest();
}
}


说明:

由于静态嵌套类的本质就是一个静态类,所以其实例对象的初始化不需要也不能像内部类那样需要绑定一个外围类对象。

由于静态嵌套类没有像内部类那样绑定外部类对象,所以也就不存在静态嵌套类不能访问其外围类的成员这种说法。

0 0