| Author |
Mock trip up question Explained, Shadowing vs Overriding
|
Robert Elbourn
Ranch Hand
Joined: Oct 15, 2007
Posts: 69
|
|
class Alpha { int over =1; public int getOver() { return over; } } class Beta extends Alpha { int over = 2; public int getOver() { return over; } } public class Gamma extends Beta { int over = 3; public static void main(String[] args) { new Gamma().go(); } public int getOver() { return over; } void go() { Beta b = new Gamma(); Alpha a = new Gamma(); //statement 1 System.out.println(super.over+" "+b.over+ " "+a.over); //statement 2 System.out.println(super.getOver()+" "+b.getOver()+ " "+a.getOver()); } } I fell for this one last night in the mock test, as with overriding, VARIABLES are not overridden, only METHODS are. I have added in the methods to illustrate the perceived expected response of overriding and polymorphism, you should be able to get this running on your pc. Statement 1 is part of the test, and the result looks like it could be 2 3 3 however its actually 2 2 1, as the object is referring to variables and not methods. However Statement 2 shows what we might have expected with overridden methods. 2 3 3. And you can not clearly see the difference. The fact that the variable "over" is repeated is an example of shadowing
|
 |
vatsalya rao
Ranch Hand
Joined: Feb 14, 2007
Posts: 63
|
|
|
A nice one Robert!!.Thanks for posting
|
 |
Fu Dong Jia
Ranch Hand
Joined: May 23, 2007
Posts: 131
|
|
|
Thanks!
|
who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12927
|
|
|
Robert, please quote your sources.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Robert Elbourn
Ranch Hand
Joined: Oct 15, 2007
Posts: 69
|
|
|
Source is Mock Exam on K&B disk Question 31:51
|
 |
 |
|
|
subject: Mock trip up question Explained, Shadowing vs Overriding
|
|
|