Submitted by c-admin on Tue, 05/28/2019 - 01:22
Question:
Given:
class StaticTest{
void m1(){
StaticTest.m2(); // 1
m4(); // 2
StaticTest.m3(); // 3
}
static void m2(){ } // 4
void m3(){
m1(); // 5
m2(); // 6
StaticTest.m1(); // 7
}
static void m4(){ }
} Which of the lines will fail to compile?
Select 2 options
A. 1
B. 2
C. 3
D. 4
E. 5
F. 6
G. 7
Answer and Explanation (Click to expand) Explanation:
To call an instance method, you need to use the reference that points to an object of that class. When you call an instance method from another instance method, you don't need a reference because "this" is implicit.
You can call a static method from either a static or an instance method. No object reference is required. You can call it by using the name of the class or you can omit that as well.
At //3, you are trying to call an instance method from another instance method. Therefore, you need to either specify an object reference or you can rely on this if you omit it. However, you cannot do StaticTest.m3() because Static Test is not a valid reference that points to an object of class Static Test.
Same thing happens at //7.