• 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 ....

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class Test29{

public static void main(String args[])
{
S2 s2=new S2();
s2.display();
}
}


class S1{
String s="S1";
void display(){
System.out.println(s);
}
}
class S2 extends S1{
String s="S2";
}

the above example displays :S1
Please tell me if the method has been inherited ,why it is not displaying S2.

------------------
Cheers~
Ravindra Gupta
ravindra_gupta@123india.com
 
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
S2 is inheriting S1's display() method and working fine. What's confusing is what it's printing it out - because you've got a String s variable in both classes. S2 inherits S1's String s and that's what the display() method is using. If you declare and initialise a class member variable with the same name in a parent and a child class, you will always end up with a variable set to the value specified in the parent class when you create an instance of the sub-class. You can either change the value in the constructor of the sub-class or change it after the instance is created.
So if you want to set s to something different for the S2 sub-class, you need to set it in a constructor like this:-
class S2 extends S1{
S2()
{
s = "S2";
}
}
Hope that helps,
Kathy
 
Ranch Hand
Posts: 198
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Overriding a method in the sub class is valid. But the same with a variable is termed as shadowing. The variable in the subclass shodows the variable in the super class. If the method display() was in the subclass it prints the subclass value. But outside of the sub class this variable is illegal, hence super class's value is printed.
HTH
 
Danger, 10,000 volts, very electic .... tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic