• 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

please explain This Code

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
abstract class D {String s1 = "D";
String getS1()
{return s1;}}
class E extends D {String s1 = "E";
String getS1()
{return s1;}}
class F {
public static void main (String[] s) {
D x = new E();
System.out.print(x.s1 + x.getS1());
}}

I was Expecting EE output
but the output is DE
please Explain How
 
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Akhilesh Yadav:
abstract class D {String s1 = "D";
String getS1()
{return s1;}}
class E extends D {String s1 = "E";
String getS1()
{return s1;}}
class F {
public static void main (String[] s) {
D x = new E();
System.out.print(x.s1 + x.getS1());
}}

I was Expecting EE output
but the output is DE
please Explain How



Just remember that variable is determined during compile time (instance x is type D) and which method get invoke is determined during runtime (the actual object is type E as you expected). hth.
 
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The o/p is quite obvious. Run time polymorphism is only for methods and not instance variables. Which variable called will depend on the reference type at compile time. Hence the O/P DE.
 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Variable depened upon the instance where as Method depends upon the Type of Object created.
So here the instance is of Type D, which outputs the s1 as "D" . Object Type is of E,which calls the method in it,takes the instance variable of it,that is s1 as "E" and so prints E.
Hope your dount got cleared.

Thanks
Harish
 
Could you hold this kitten for a sec? I need to adjust this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic