在下面,我们看到对于b类来说他的嵌套层次是:acessmethod-〉a-〉b,那么访问方法如下:
| class b { void h() { system.out.println("h()"); g(); f(); } |
acessmethod和a来说对b,都是透明的,直接调用。嵌套类实例化的顺序:有外到里!acessmethod-〉a-〉b
调用代码如下:
| acessmethod am = new acessmethod(); acessmethod.a a = am.new a(); acessmethod.a.b b = a.new b(); b.h(); |
这里很有意思的一点,’.new’语法产生了正确的作用域。
疑问:下面我们来看一下在b.h()中怎样调用a1.g()方法?
我们是否可以在b中调用a1.g()方法,在b.h()方法中原则上可以这样调用a1.g()但是a1没有实例化,所以这样是错误的,也就是在b中无法调用a1中的非静态方法了。
假设:如果a1.g()为static类型,那么在b中可以这样调用a1种的方法:a1.this.g();
但是这是不可能的,因为在a1.g()不可能定义为static类型,详细看下面的问题1(问题1:在什么情况下可以定义static 方法),这是一个缺点吧,但是可以使用嵌套类来解决了。
| /** * 从多层嵌套类中访问外部类的成员. “.new“语法产生了正确的作用域 */ public class acessmethod { private void f() { system.out.println("f()"); } class a1 { private void g() { system.out.println("a1 - g()"); } } class a { private void g() { system.out.println("g()"); } class b { void h() { system.out.println("h()"); g(); f(); } } } public static void main(string[] args) { acessmethod am = new acessmethod(); acessmethod.a a = am.new a(); acessmethod.a.b b = a.new b(); b.h(); } } |
运行结果:h()
| g() f() |
问题1:在什么情况下可以定义static 方法?
只有在顶层类中定义,或者在静态内部类中定义,看下面的例子
| public class test { static void t(){} class t2{ //!错误,the method a cannot be declared static; //static methods can only be declared in a static or top level type //static void a(){} } static class t3{ static void a(){} } } |
闽公网安备 35060202000074号