0

I've just started learning Java and I am stuck at this MCQ:

Assume class Temp is defined as belowand the statment Temp a= new temp() is successfully executed Which of the statement is illegal in Java?

class Temp {
 public static int i;
 public void method1() { }
 public static void method2() { }
}

A. System.out.println(i);

B. Temp.method1();

C. a.method1();

D. Temp.method2();

The answer is B, but I can't understand why. Is it because a void method cannot be defined using the dot notation unless it's static?

nerv21
  • 21
  • 1
  • 3
  • `method1` is not static, in other words you have to create a `Temp` class instance before calling this method. –  Oct 12 '17 at 11:58
  • 1
    It has nothing to do with the return type of `void`. You simply can't call an *instance* method *statically*. – David Oct 12 '17 at 11:58
  • Are you sure B is the only illegal one? What about A? – Henry Oct 12 '17 at 12:03
  • @Henry exactly! I thought the answer is A, the reason being i is not initialized? – nerv21 Oct 12 '17 at 12:07
  • Not because of that, but it should be `System.out.println(Temp.i);` – Henry Oct 12 '17 at 12:15
  • @Henry: I guess the difference is that `System.out.println(i);` is correct when beeing called from class Temp (In which case you don't need to add the classname in front of it) but `Temp.method1();` is wrong no matter from where in your code you try to call it. – OH GOD SPIDERS Oct 12 '17 at 12:23
  • @OHGODSPIDERS that would be an explanation, but on the other hand "class Temp is defined as below" and there is no further code in it. – Henry Oct 12 '17 at 12:28

1 Answers1

0

Because method1 is non-static method. You can use methods with class names only if they are static. Look here for more details.

saidfagan
  • 841
  • 2
  • 9
  • 26