Forums Register Login

Parent Child Relation

+Pie Number of slices to send: Send
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'.
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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.
+Pie Number of slices to send: Send
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".
Listen. That's my theme music. That's how I know I'm a super hero. That, and this tiny ad told me:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 778 times.
Similar Threads
same method inheritance
plz explain and tell out put
Super and this within same method/constructor
any one give be the explanation for the code above and y it prints the output as pare
Constructor,why displaying null on this program
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 03:18:17.