3

I am trying to use this wavRead(filename) but am getting the message 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);
}
n00begon
  • 3,503
  • 3
  • 29
  • 42
erp
  • 2,950
  • 9
  • 45
  • 90

5 Answers5

12

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
4

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.

You need to make an instance of your class, and call wavRead on it, or make wavRead and mySamples static:

public static void main(String[] args) {
    Sound instance = new Sound();
    ...
    instance.wavRead(fileName);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You need to make a Sound object before you can call wavRead on it. Something like

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

The only way to call a non-static method from a static method is to have an instance of the class.

newuser
  • 8,338
  • 2
  • 25
  • 33
0

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.

Chirag Kathiriya
  • 427
  • 5
  • 14