0

I've been doing some tutorial on inheritance abstract class, and I pass an array to a function for a calculation of total price. But then, when I tried to call the function in the main, it didn't work and I've got some error according the method call.

Here is my calculation code in subclasses :

public double calcPrice(String[] a, int[] qty, int num){
    int i =0;
    for(i=0;i<=num;i++) { 
        if (a[i]=="a")
            price=24.90;
    }

    double tot=price+qty[i];
    return tot;
}

This is my method call in the for loop. I don't know how to call the method as the error says "non-static method calcPrice() cannot be referenced from a static context"

for(int i=0;i<=num;i++) {
    System.out.println("\t"+a[i]+"\t\t\t"+qty[i]+" "+calcPrice());
 }
deenaiena
  • 19
  • 1
  • 4

3 Answers3

2

The main method is static, and can't call non-static code. You have 2 solutions.

  • Create an instance of the class performing the calculation, and call calcPrice on that instance.

  • make calcPrice static.

I suggest option one as you've been doing research on classes. This would be good practice for you.

Also do not compare variable a to "a" with ==. Use .equals instead. Check this link for why.

Edit:

I'm not sure how an abstract class plays into this as you have no abstract methods needing implementation.

public class CalcClass{
    public double calcPrice(String[] a, int[] qty, int num){
        int i =0;
        for(i=0;i<=num;i++) { 
            if ("a".equals(a[i]))
               price=24.90;
        }

        double tot=price+qty[i];
        return tot;
    }
}

public class MainClass{
    public static void main(String[] args){
        //create instance of calc class
        CalcClass c = new CalcClass();
        //call calc price method on calcclass
        c.calcPrice(a, new int[]{1}, 1};
    }
}
Community
  • 1
  • 1
William Morrison
  • 10,953
  • 2
  • 31
  • 48
1

Changed to-

public static double calcPrice(String[] a, int[] qty, int num){
    ...
}

You should create an object before you do a call from main. Say you have a class-

public class Test {

    public void someMethod(){

    }

    public static void main(String... args){

      // Create an object first
      Test t = new Test();

      // Now you can use that non-static method someMethod
      t.someMethod();

    }

}

For static method, they exist on load.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
0

You will need to create instance in order to call you method since your method is not static.

making you methos static will enable you to use it without creating instance of the class.

you may want to read about Static Methods here

Mzf
  • 5,210
  • 2
  • 24
  • 37