java 外部类可以调用内部类的方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16929612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:24:57  来源:igfitidea点击:

Can outer classes call methods of its inner class?

javaclassscope

提问by sherrellbc

I have code establishing a server connection upon the event that a user clicks a specific button. I created an inner class to listen for the action. Within the single method I have in the inner class, I also establish that server connection mentioned earlier.

我有代码在用户单击特定按钮时建立服务器连接。我创建了一个内部类来监听动作。在内部类的单一方法中,我还建立了前面提到的服务器连接。

My question is, can the Socket connection only be utilized from within the "inner" class? Or, can the outer class proceed with communication with said server?

我的问题是,只能在“内部”类中使用 Socket 连接吗?或者,外部类是否可以继续与该服务器进行通信?



I do, however, understand that the inner class has unrestricted access to the outer class(as if it werethe outer class. My question is the other way around.

但是,我确实理解内部类可以不受限制地访问外部类(就好像它外部类一样。我的问题是相反的。

回答by Juned Ahsan

Create an instance like this and access what you want:

创建一个这样的实例并访问您想要的内容:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

回答by Stephen C

All methods declared on the inner class are accessible... whether they are declared as publicor ... private.

在内部类上声明的所有方法都是可访问的......无论它们是声明为public还是 ... private

If the inner methods are staticthen they can always be called by code in the outer class. You just need to qualify the method name with the inner class name.

如果内部方法是,static那么它们总是可以被外部类中的代码调用。您只需要使用内部类名称限定方法名称。

Otherwise, the outer class code needs a reference for an instance of the inner class to call methods on it. (But that's normal.)

否则,外部类代码需要内部类实例的引用来调用其上的方法。(但这很正常。)



(If you were asking about whether an inner class could call methods on the outer class, it is a bit more complicated. Most of the above applies, but if the inner class is NOT staticit can alsocall instance methods on its outer class via this.)

(如果你问一个内部类是否可以呼吁外部类的方法,这是一个比较复杂的。大部分的上述适用,但如果内部类是不是static呼吁通过其外部类的实例方法this。 )

回答by mkumar0304

Yes ,you can achieve this look below sample code

是的,您可以在示例代码下方实现这种外观

    currentDateMinutes=getDateAndTime();
    System.out.println("DATE & TIME:"+new JobSchedulerUtil().new TaskScheduler(currentDateMinutes).timeNow()); 

Above code JobSchedulerUtil class is an outer class with having getDateAndTime() method and an inner class TaskScheduler with timeNow() method.

上面的代码 JobSchedulerUtil 类是具有 getDateAndTime() 方法的外部类和具有 timeNow() 方法的内部类 TaskScheduler。