简体   繁体   English

Java:在另一个类中调用方法

[英]Java: Calling a method in another class

I am trying to get my first class to run a method ShutDownServer in my second class. 我正在尝试让我的第一堂课在第二堂课中运行方法ShutDownServer What do I need to change for the method to be called? 我需要更改什么才能调用该方法?

My First Class (I've removed all extra code): 我的头等舱(我已经删除了所有多余的代码):

//imports the other class
package examples;
import examples.Class2;

//Below line has error: The method ShutDownServer() is undefined for the type Class2
Class2.shutDownServer();

My Second class: 我的第二堂课:

package examples;

public class Class2 {
    public void shutDownServer() {
        System.out.println("It Works?");
    }
}

Either make the shutDownServer method static... 要么将shutDownServer方法设置为静态...

public static void shutDownServer() {

Or, simply instantiate a Class2 object and call the method... 或者,只需实例化Class2对象并调用该方法...

Class2 server = new Class2();
server.shutDownServer();

The method signature for shutDownServer will depend on the nature of the design choices you make with your application. shutDownServer的方法签名将取决于您对应用程序做出的设计选择的性质。

And you don't need to have that import for examples.Class2, given that the calling object is in that package already: package examples; 而你并不需要有因为调用对象是在该包已,即对进口examples.Class2: package examples;

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

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