简体   繁体   English

如何调用另一个类内部的类的方法?

[英]How to call a method of a class that is inside another class?

package collections; 
public class Construct 
  { 
    class Inner
      { 
        void inner() 
          { 
            System.out.println("inner class method "); 
          } 
      } 
    public static void main(String[] args) 
      { 
        Construct c=new Construct(); 
      } 
  } 

How to call a method of the inner class? 如何调用内部类的方法? How to create an object to call a method of the inner class? 如何创建一个对象来调用内部类的方法?

Use this: 用这个:

Inner inner = new Construct().new Inner();
inner.inner();

Inner class is a nested class. 内部类是嵌套类。 Nested classes can be static or not. 嵌套类可以是静态的,也可以不是静态的。 If static then its called static nested class and if not its called inner classes. 如果是静态的,则称为静态嵌套类,如果不是,则称为内部嵌套类。

Non-static nested classes hold a reference to the Outer class that they are nested within. 非静态嵌套类包含对嵌套在其中的Outer类的引用。

What you have is an inner nested class, so we need to instantiate the inner class with a reference from the Outer like so: 您拥有的是一个内部嵌套类,因此我们需要使用来自外部的引用实例化内部类,如下所示:

Construct c = new Construct();
Inner inner = c.new Inner(); //using reference to create inner
inner.inner(); //Calling method from inner.

Depends upon whether your class is static or non-static. 取决于您的类是静态的还是非静态的。

For non-static inner class, use this: 对于非静态内部类,请使用以下命令:

Inner inner = new Construct().new Inner();
inner.inner()

For static inner-class, use this: 对于静态内部类,请使用以下命令:

InnerStatic inner = new Construct.Inner();
inner.inner()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM