• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Mock trip up question Explained, Shadowing vs Overriding

 
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A nice one Robert!!.Thanks for posting
 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks!
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Robert, please quote your sources.
 
Robert Elbourn
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Source is Mock Exam on K&B disk Question 31:51
reply
    Bookmark Topic Watch Topic
  • New Topic