This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Mock trip up question Explained, Shadowing vs Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Mock trip up question Explained, Shadowing vs Overriding" Watch "Mock trip up question Explained, Shadowing vs Overriding" New topic
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14279
    
  21

Robert, please quote your sources.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Robert Elbourn
Ranch Hand

Joined: Oct 15, 2007
Posts: 69
Source is Mock Exam on K&B disk Question 31:51
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Mock trip up question Explained, Shadowing vs Overriding