解释在Java中访问内部类的方法? [英] explain the way to access inner class in java?

查看:56
本文介绍了解释在Java中访问内部类的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Outer {    
    class Inner {       

    }    
}

public class Demo {
    public static void main(String args[]) {

        Outer o = new Outer();
        Outer.Inner inner = o.new Inner();    

    }    
}

我为Inner类对象创建引用的方式类似于访问Outer类中的static成员?
请您解释一下其背后的机制?

the way I create a reference for Inner class object is something like accessing static member in Outer class ?
could you please explain the mechanism behind this ?

推荐答案

我为Inner类对象创建引用的方式类似于访问Outer类中的static成员

the way I create a reference for Inner class object is something like accessing static member in Outer class

完全没有-因为您正在使用Outer的实例来访问Inner的构造函数,所以这非常类似于访问Outer类的 instance 成员. ,而不是其static成员.声明中的Inner类名称用其外部类Outer的名称限定,以避免与顶级类的命名冲突.

Not at all - since you are using an instance of the Outer to access the constructor of the Inner, this is very much like accessing an instance member of the Outer class, not its static member. The name of the Inner class in the declaration is qualified with the name of its outer class Outer in order to avoid naming conflicts with top-level classes.

原因很容易理解:Inner是一个非静态内部类,因此需要引用Outer.它隐式地这样做,但是必须将引用传递给幕后的构造函数.因此,您可以在Outer的实例上调用Inner的构造函数.

The reason for that is easy to understand: Inner is a non-static inner class, so it needs to reference an Outer. It does so implicitly, but the reference must be passed to the constructor behind the scene. Therefore, you call a constructor of Inner on an instance of Outer.

制作static类实例的语法与制作常规类实例的语法相似,不同的是嵌套类的名称必须以其外部类的名称作为前缀-即遵循static语法:

The syntax for making instances of static classes is similar to the syntax for making instances of regular classes, except the name of the nested class must be prefixed with the name of its outer class - i.e. following the static syntax:

class Outer {    
    static class Inner {       

    }    
}

public class Demo {
    public static void main(String args[]) {
        Outer.Inner inner = new Outer.Inner();    

    }    
}

这篇关于解释在Java中访问内部类的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆