• 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

Inheritance Doubt

 
Ranch Hand
Posts: 751
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi guys, I was experimenting earlier. Why is it that we are allowed to redefine another member of the same type and name of that in an abstract class?

public abstract class A
{
int i;

public int getI()
{
return i;
}
}

class B extends A
{
int i;

public int getI()
{
return i;
}
}


What happens here? Whose i gets returned?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is called "shadowing" a variable, and it's a very bad practice; confusing things can happen. In particular, calling B.getI() will return B's copy of "i", but calling super.getI() in class B will return A's version of "i". Worse, any methods in A that use "i" will continue to use A's copy of "i", while any methods in B that use "i" will use B's copy. This could lead to subtle and hard-to-find bugs.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
IDE's like Eclipse can be configured to raise warnings or even compile time errors for such code.
reply
    Bookmark Topic Watch Topic
  • New Topic