• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

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: 24204
44
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: 24204
44
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".
 
Politics is a circus designed to distract you from what is really going on. So is this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic