• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Doubt

 
Venkat01
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Super
{ int index = 5;
public void printVal()
{ System.out.println( "Super" );
}
}
class Sub extends Super
{ int index = 2;
public void printVal()
{ System.out.println( "Sub" );
}
}
public class Runner
{ public static void main( String argv[] )
{ Super sup = new Sub();
System.out.print( sup.index + "," );
sup.printVal();
}
}
What will be printed to standard output?
a) The code will not compile.
b) The code compiles and "5, Super" is printed to standard output.
c) The code compiles and "5, Sub" is printed to standard output.
d) The code compiles and "2, Super" is printed to standard output.
e) The code compiles and "2, Sub" is printed to standard output.
f) The code compiles, but throws an exception.
Why is C right over here. I should have been E). Can anyone clarify.
 
paul wheaton
Trailboss
Pie
Posts: 21673
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with c. You can't override class attributes.
The object is of type Sub, but the reference is of type Super. Sub has all the Super stuff. If Sub has a methd called foo(), you wouldn't have access to it with a Super reference. So the Super reference accesses the only "index" it knows about. When it tries to call printVal(), it is overriden, so the Sub version must be called.
 
Venkat01
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Paul,
Thanks for the reply. But my only point is that i am calling "sup.index" here which should access the base class 'sup' and call its variable '2', but why in the world it is calling super classes index. I am confused. Can you please clarify more. The other part of method answer is understood by me.
To sum up, if i use a super classes handle and create a object of the base class and still access the same handle to print the member variable of the super class, it should work like above. Can we generalise this.
 
paul wheaton
Trailboss
Pie
Posts: 21673
Firefox Browser IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't override attributes.
index is an attribute.
Therefore, you can't override index.
Any Sub object will have two index attributes. One in the Super part and one in the Sub part. A Super reference will see the Super index and a Sub reference will see the Sub index.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic