Query regarding calling parent's class method which is overridden in child class???

P

parkarumesh

Hi,

I have a superclass say

public class Parent {

public String go() {
.
.
.
}
}

Assume i have written some code in the go method of parent class.

Also i have a child class say,

public class Child {
public String go() {
.
.
.
super.go();
}
}

I have overridden the go method of parent class in the child class. I
write some code in the go() of Child class and give a call to Parent's
go() using super.go() as I want to execute the functionality written
in the go() of Parent.

I want to know is it logical to call super.go(), when go is actually
overridden by child class.

Regards,
parkarumesh
 
I

Ingo R. Homann

Hi,

...
I want to know is it logical to call super.go(), when go is actually
overridden by child class.

Yes, it's a (more or less ;-) common practise. That's what the "super"
keyword is used for (in this context).

The only other possibilty is not very common, IMHO:

class Sub extends Parent {

void go() {
...
}

void bar() {
super.go();
// here it is more common to call this.go()
// but of course this also depends on your use-case
}

}


Ciao,
Ingo
 
L

Lew

Yes, it's a (more or less ;-) common practise. That's what the "super"
keyword is used for (in this context).

The only other possibilty is not very common, IMHO:

class Sub extends Parent {

void go() {
...
}

void bar() {
super.go();
// here it is more common to call this.go()
// but of course this also depends on your use-case
}

}

Ingo is absolutely right. To provide a little more detail, let's say a parent
(possibly abstract) class provides part of the setup, but wants the child
class to do the rest.

<sscce source="Child.java">
abstract class Parent
{
public void init()
{
System.out.println( "Parent.init()" );
establishConnection();
doMoreParentalGuidance();
}
private void establishConnection()
{
System.out.println( "Parent.establishConnection()" );
}
private void doMoreParentalGuidance()
{
System.out.println( "Parent.doMoreParentalGuidance()" );
}
}

public class Child extends Parent
{
public void init()
{
System.out.println( "Child.init()" );
super.init();
doStuffOnlyChildNeeds();
}
private void doStuffOnlyChildNeeds()
{
System.out.println( "Child.doStuffOnlyChildNeeds()" );
}
public static void main( String [] args )
{
Parent parent = new Child();
parent.init();
}
}
</sscce>

The call to parent.init() will polymorphically call the Child version of
init(), which in turn invokes the Parent version through the super call.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top