Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Parent Child Relation

 
Tarun Singh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class SuperParent
{
public void printMessage()
{
System.out.println("Super Parent");
}
}
class Parent extends SuperParent
{
public void printMessage()
{
System.out.println("Parent");
}
}
public class Child extends Parent
{
public void printMessage()
{
System.out.println("Child");
}
public static void main(String s[])
{
???
}

}
How to call printMessage() of SuperParent class so, the output should be 'Super Parent'.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, of course, you can call it on an instance of SuperParent -- i.e., nothing stops you from doing this in Child.main():

SuperParent sp = new SuperParent();
sp.printMessage();

But I suspect what you're asking is whether there's any way for an instance of Child to invoke SuperParent's printMessage() on itself. The answer is no -- Java simply doesn't allow it, so don't waste any energy trying to figure out a way!
 
Tarun Singh
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest Friedman,
My question is if i want to call SuperParent method printMessage() without creating it's Object.
we can call super.printMessage(), it will give you output "Parent". So there is any way to call SuperParent Class from the Child without creating it's object.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As I said, no. A class can call methods it directly inherits from its superclass, but it can't call methods from the "super-superclass".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic