-2

Code is

public class ctorsandobjs {
    private int a;
    public int b;

    public ctorsandobjs(String arg)
    {
        System.out.println("I got " + arg);
    }

    public void add(int a,int b)
    {
        System.out.println("Addition is " + String.valueOf(a+b)); 
    }
    public static void main(String args[])
    {
        ctorsandobjs c = new ctorsandobjs("You");
        c.a = 12;
        c.b = 15;
        add(c.a,c.b);                      //compiler shows error here
    }
}

I am using Eclipse Luna IDE and JDK 8 ... can you tell me why compiler is showing error here..... "Cannot make a static reference to a non static method add(int,int) from the type ctorsandobjs"

I am new to JAVA...

and if possible suggest a solution

Parag
  • 55
  • 6

3 Answers3

0

You cannot reference non-static members (private int a; public int b) from within a static function.

Lilith Daemon
  • 1,473
  • 1
  • 19
  • 37
0

The add method is not a static method, so you need to call it on an instance of the class ctorsandobjs, for example like this:

c.add(c.a,c.b);
Jesper
  • 202,709
  • 46
  • 318
  • 350
0

add is a non-static method and so you have to invoke it from the object of a class You have to do:

c.add(c.a, c.b);
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47