-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
  • 43
  • 4

3 Answers3

0

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

Chris Britt
  • 1,443
  • 1
  • 17
  • 35
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
  • 195,030
  • 44
  • 313
  • 345
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
  • 13,804
  • 1
  • 24
  • 44