memelord23
memelord23

Reputation: 124

Java static main also codingBat

public class CodingBat {
    public static void main(String[] args) {
        System.out.println(sumDouble(5,5));
    }

    public int sumDouble(int a, int b) {
        if( a ==b) {
            return 2*a + 2* b;
        } else{
            return a + b;
        }
    }
}

So I made this code, and I'm really confused why it doesn't work unless I write static between the public int sumDouble, because I was practicing on codingBat, and to answer the question they did not involve static, but then how do they test code. Do they use the main? I mean you have to to get the code running right? So to my knowledge, static means that every object of this class will all contain the same value.But I don't see the relevance of this error.

"Cannot make a static reference to the non-static method"

Thank you for your help :D

Upvotes: 0

Views: 237

Answers (3)

Ofer
Ofer

Reputation: 5219

You need to create an object in order to use this method

public class CodingBat {
    public static void main(String[] args){
        CodingBat obj = new CodingBat();
        System.out.println(obj.sumDouble(5,5));
    }
    public int sumDouble(int a, int b) {
        if( a ==b){
            return 2*a + 2* b;}
        else{
            return a + b;}
    }

}

Upvotes: 0

Stultuske
Stultuske

Reputation: 9437

Either you call it through a static context, meaning like you do (or, from another class, by: ClassName.methodName(); )

Or, you have to call it as an instance method, which it is, if you don't declare it static.Then, however, you'll need an instance to call it through:

public static void main(String[] args){
        CodingBat cB = new CodingBat();
        System.out.println(cB.sumDouble(5,5));
    }

Upvotes: 0

Ankur Singhal
Ankur Singhal

Reputation: 26077

and I'm really confused why it doesn't work unless I write static between the public int sumDouble,

Yes, static is required

Since the main method is static and the sumDouble() method is not, you can't call the method without creating object of class. You cannot refer non-static members from a static method.

Either make method static or create object as below and then access method.

CodingBat obj = new CodingBat();
 System.out.println(obj.sumDouble(5,5));

Refer here for more

Upvotes: 1

Related Questions