• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explain ...

 
Shiaber Shaam
Ranch Hand
Posts: 252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test extends Super {

int x = 20; //1

public void test() {
System.out.println("x = " + x);
}

public static void main(String[] arg) {
Super s = new Test(); //2
s.test(); //3
}
}

class Super {
int x = 10; //4

public void test() {
System.out.println("x = " + x);
}
}
A : x = 10
B : x = 20
C : The program cannot be compiled due to line //1.
D : The program cannot be compiled due to line //2.
E : The program cannot be compiled due to line //3.
F : The program cannot be compiled due to line //4.

O/P B...Why....
 
Peter MacMillan
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even though the type of s is Super, the type of the object that it references is of type Test. This is possible because Test is a Super by virtue of inheritance. The test() method overrides the test() method of the Super class, and when you call s.test() you call that method (the one in Test) because of what the object is.

Hope that helps.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x=20
What Is Variable Hiding and Shadowing?
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In simple, instance method looks for object not for reference type.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic