• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static behaviour  RSS feed

 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By compile the below pgm, I'm getting the Output as:

"Goodmorning Dick"

How? it should be "Goodmorning Richard".

class Super
{
static String greeting()
{
return "Goodmorning";
}

String name()
{
return "Richard";
}
}

class Sub extends Super
{
static String greeting()
{
return "Hello";
}

String name()
{
return "Dick";
}
}

class Test1
{
public static void main(String[] args)
{
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't tell what you're interested in, whether you've made a mistake here, or whether you're learning about polymorphism, or what. But in any case because "name" is not static, it's polymorphic; the JVM chooses what method to call at runtime based on the actual type of the object. On the other hand, greeting is static, so it's up to the compiler to choose the method to call based on the compile-time type of the reference you call the method on.

So because the type of the reference "s" is "Super", Super.greeting() is called; but because the actual object is an instance of Sub, Sub.name() is called.

Let us know if you need more help here.
 
Niyas Ahmed Sheikh
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much for your reply. Yes I am learning/having confusiion with the polymorphism. Now it has been clarified.

I slightly changed the coding: Now the o/p is: Goodnight Richards.

Whether JVM at the runtime look at only methods. not members

class Super
{
String str = "Richards";

static String greeting()
{
return "Goodnight";
}


}

class Sub extends Super
{
static String greeting()
{
return "Hello";
}

String str = "Dick";

}

class Test1
{
public static void main(String[] args)
{
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.str);
}
}
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As you've discovered, only methods are polymorphic. Redeclaring a variable in a base class is often called "shadowing" or "hiding" the variable, and it's almost always a bad thing; it leads to difficult-to-understand behavior.

The right thing to do is to initialize the variable to a type-specific value in the class's constructor -- i.e.,



Now Test1 will print "Goodnight, Dick" because the copy of "s" in a Sub instance is set to "Dick" when the object is created.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!