This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock trip up question Explained, Shadowing vs Overriding

 
Robert Elbourn
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A nice one Robert!!.Thanks for posting
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
 
Robert Elbourn
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source is Mock Exam on K&B disk Question 31:51
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic