• 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

Parent Child Relation

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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'.
 
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
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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
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
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".
reply
    Bookmark Topic Watch Topic
  • New Topic