Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Override question

Status
Not open for further replies.

pacsinte

Programmer
Oct 5, 2003
10
0
0
CA

Hello,

I have an abstract class Base which implements interface If1.
Classes D1, D2 and D3 are derived from Base.
Right now, the "common" methods from If1 are implemented only in the Base class and the specialized methods are implemented directly in the derived classes. The "common" methods are not implemented in any way in the derived classes (they are just inherited). For example:

interface If1 {
void common_m1();
void m2();
}

public abstract class Base Implements If1 {

public void common_m1() {
// implementation
}

}

public class D1 extends Base {

public void m2() {
// D1 specific implementation
}

}

public class D2 extends Base {

public void m2() {
// D2 specific implementation
}

}

public class D3 extends Base {

public void m2() {
// D3 specific implementation
}

}

There is a proposition to implement all the methods in the Base class and to override all the methods in the derived classes. For common methods, the method from the derived class will use super to call the base class implementation, like this:

interface If1 {
void common_m1();
void m2();
}

public abstract class Base Implements If1 {

public void common_m1() {
// implementation
}

public void m2() {
// dummy implementation
}
}

public class D1 extends Base {

public void common_m1() {
super.common_m1();
}

public void m2() {
// D1 specific implementation
}

}

public class D2 extends Base {

public void common_m1() {
super.common_m1();
}

public void m2() {
// D2 specific implementation
}

}

public class D3 extends Base {

public void common_m1() {
super.common_m1();
}

public void m2() {
// D3 specific implementation
}

}

Is there any reason why the second solution is better than the first?

Thank you,
Bobby
 
In my opinion (could be wrong!), there is no real point in what the 2nd solution is doing, because D1,D2,D3 all extend Base, and so automatically have access to the method common_m1().

I could be missing some semantics though ...
 
AFAIK, there's only one slightly difference between those two implementations.

Let's imagine that m2() calls commonm1().

In the first case, the parent class implementation of commonm1() would be loaded. In the second case, would be the child one.

Cheers.

Dian

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top