-1
class ClassB {
   int c=0;
   public static void main(String [] args) {
      ClassA cla = new ClassA();

      c=cla.getValue();
   }
}

class ClassA {
   int value = 0;
  public int getValue() {
     ClassA obj=new ClassA(); 
     return obj.value;
  }
}

I want to 'int value' of ClassA in 'int c' of class B. The above code shows the error "non static variable c cannot be referred from a static context". Please provide the correct coding for me as I am stuck.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

3 Answers3

0

Of course, becuase you can't call a non-static method without instantiating the object that contains this method fisrt, either make all the methods and fields static, or instantiate the class:

class ClassB {
   static int c=0;
   public static void main(String [] args) {
      ClassB clb = new ClassB(); 
      c= clb.getvalueA();
   }
   public int getvalueA(){
      ClassA cla = new ClassA();      
      return cla.getValue();
   }
}

class ClassA {
   int value = 0;
   public int getValue() {
      return value;
   }
}
Pramod Tapaniya
  • 1,228
  • 11
  • 30
0

Variable c in class B is not static and main block is static block that's why it showing error.You can not reference non static field from static context.

-1
public class Main {
  public static void main(String[] args) {
    int retVal;

    TestClass a = new TestClass(20);
    retVal = a.value;

    System.out.println("Value of a: "+retVal);
  }
}
class TestClass {
  int value;
  public TestClass(int value) {
    this.value = value;
  }
  public int getValue() {
    return this.value;
  }
}