Java 不能调用非静态方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19149504/
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
Can't call non static method
提问by erp
I am trying to use this wavRead(filename)
but am getting the message cannot make a static reference to a non static method
.
我正在尝试使用它,wavRead(filename)
但收到消息cannot make a static reference to a non static method
。
I could simply make it static and that solves my problem, but how would do it without going that route. I would like to keep the method non static.
我可以简单地将其设为静态,这解决了我的问题,但是如果不走那条路怎么办。我想保持该方法非静态。
Here is a bit of the code to let you see whats going on:
下面是一些代码,让你看看发生了什么:
public class Sound {
double [] mySamples;
public static void main(String[] args){
String filename = null;
System.out.println("Type the filename you wish to act upon.");
Scanner scanIn = new Scanner(System.in);
filename = scanIn.next();
wavRead(filename);
}
public void wavRead(java.lang.String fileName){
mySamples = WavIO.read(fileName);
}
采纳答案by Sotirios Delimanolis
Create an instance of your class
创建类的实例
public static void main(String[] args){
String filename = null;
System.out.println("Type the filename you wish to act upon.");
Scanner scanIn = new Scanner(System.in);
filename = scanIn.next();
Sound sound = new Sound();
sound.wavRead(fileName);
}
It's an instance method, it requires an instance to access it. Please go through the official tutorials on classes and objects.
回答by Dawood ibn Kareem
You need to make a Sound
object before you can call wavRead
on it. Something like
您需要先创建一个Sound
对象,然后才能调用wavRead
它。就像是
Sound mySound = new Sound();
mySound.wavRead(filename);
Static just means that you don't need to have an instance of the class that the method belongs to.
静态只是意味着您不需要拥有该方法所属的类的实例。
回答by dasblinkenlight
You cannot call non-static methods or access non-static fields from main
or any other static method, because non-static members belong to a class instance, not to the entire class.
您不能从main
或任何其他静态方法调用非静态方法或访问非静态字段,因为非静态成员属于类实例,而不是整个类。
You need to make an instance of your class, and call wavRead
on it, or make wavRead
and mySamples
static:
你需要为你的类创建一个实例,并调用wavRead
它,或者 makewavRead
和mySamples
static:
public static void main(String[] args) {
Sound instance = new Sound();
...
instance.wavRead(fileName);
}
回答by newuser
The only way to call a non-static method from a static method is to have an instance of the class.
从静态方法调用非静态方法的唯一方法是拥有类的实例。
回答by Chirag Kathiriya
static method can call directly to the another static method in the same class.you dont need to create object of class. if call the non static method then first create the object of the class and call the object.non static method.
静态方法可以直接调用同一个类中的另一个静态方法,不需要创建类的对象。如果调用非静态方法,则首先创建类的对象并调用 object.non 静态方法。