java 如何从Java中的同一类调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43972284/
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
How to call a method from the same class in Java?
提问by Abdul
How can I call getDummy from main? I need this so I can pass dummy to a method in another class.
如何从 main 调用 getDummy?我需要这个,所以我可以将 dummy 传递给另一个类中的方法。
public class Test {
public static void main(String[] args) {
private int dummy = 0;
}
public int getDummy() {
return dummy;
}
}
回答by ΦXoc? ? Пepeúpa ツ
getDummyis an instance method so you need the instance
getDummy是一个实例方法,所以你需要实例
public static void main(String[] args) {
Test t = new Test();
t.getDummy();
}
and this belongs to the class
这属于班级
private int dummy = 0;
your final code could look like>
你的最终代码可能看起来像>
public class Test {
private int dummy = 0;
public static void main(String[] args) {
Test t = new Test();
t.getDummy();
}
public int getDummy() {
return dummy;
}
}
回答by phanhien1701
sry, my english very bad, but i think i can help you. first, you create a public variable out of main, in you code, you only create a local variable. next, in your main, you type : "getDummy();". good luck
对不起,我的英语很差,但我想我可以帮助你。首先,您从 main 创建一个公共变量,在您的代码中,您只创建一个局部变量。接下来,在您的主要内容中,您输入:“getDummy();”。祝你好运
回答by Haven Lin
you should be declare target object, and initialization, then you can use getDummy()
, or you can modify getDummy()
method to static .
你应该声明目标对象,并初始化,然后你可以使用getDummy()
,或者你可以修改getDummy()
方法为静态。
回答by Binyamin Regev
Is this what you mean?
你是这个意思吗?
public class Test {
private int dummy = 0;
public static void main(String[] args) {
Test test = new Test();
int dummy = test.getDummy();
}
public int getDummy() {
return dummy;
}
}
I assume private int dummy = 0;
is a property (variable) of Test
class. Calling a non-static
method from a static
method is not allowed. You create an instance of your class in the static
method and can call any of its public
methods.
我假设private int dummy = 0;
是类的属性(变量)Test
。不允许non-static
从static
方法调用方法。您可以在static
方法中创建类的实例,并且可以调用其任何public
方法。