How to override method to invoke superclass' superclass method? [duplicate] - java

This question already has answers here:
Closed 13 years ago.
Part of me thinks that this shouldn't be possible (even if it is), but I'll ask anyway.
Given the following class hierarchy (Grandparent and Parent are from a 3rd party and thus, not under my control), how would I override myMethod() in Child such that it bypasses the overridden implementation in Parent and invokes the one in Grandparent?
class Grandparent {
public void myMethod() {
// do stuff
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
}
}
Pretend that the Parent class provides a lot of other helpful behavior and is a crucial element of Child's hierarchy (in other words, I'm not looking for "make Child a subclass of Grandparent".

The idea behind inheritance is that each class defines their methods how they need, so you don't need to be inspecting any code.
It seems like you're subclassing here just to re-use code, and that's not the idea of subclassing.
Maybe you should have a helper member to do some of the tasks you need, instead of subclassing, and have both "Child" and "Parent" classes extend "Grandparent".
The main question you need to ask yourself is: "Is Child really a descendant of Parent, Grandparent or neiter?" In other words, for every instance of Child, can I say it's a Parent?
If the answer is no, then you're subclassing wrongly: inheritance is supposed to mean something, not just code re-use (i.e. Ford IS ALSO a Car, not just "Ford" uses "Car" methods).

Assuming that I couldn't touch the code in Parent or Grandparent and assuming that I'm not, as Seb suggested (and as Steve apparently agreed) simply misusing inheritance entirely:
I'd create a local instance of a Grandfather object (or a local class extending Grandfather, if it's abstract) and access its interpretation of myMethod() directly. Of course, depending on how much state information myMethod() is supposed to read and/or manipulate, the amount of work involved could be anything from "easy" to "excruciating".
It's an ugly solution, and, depending on how much state information is accessed, could be brittle as hell. But if Grandfather is reliably stable and/or myMethod() is fairly self-contained, it could work. The devil is in the details, as always.
I definitely agree with Seb that this is re-use, not inheritance. But, hey. Re-use is often a Good Thing.

Not possible.
I would create a final helper method in grandparent instead. And have this method (which is overridden) call that helper.
class Grandparent {
public final void myHelperMethod() {
// do stuff
}
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myHelperMethod();
}
}

Do you have control of the Parent class?
If so, could you add a method (myNewMethod) to the Parent that calls myMethod on Grandparent, and call myNewMethod from Child?
(I'm not a Java person, so don't know if you can only call a method in a superclass from an override of that method in a subclass)
class Grandparent {
public void myMethod() {
myHelperMethod();
}
}
class Parent extends Grandparent {
#Override public void myMethod() {
super.myMethod();
// do something else
}
public final void myNewMethod() {
super.myMethod();
}
}
class Child extends Parent {
#Override public void myMethod() {
// ??? I want to *only* do what Grandparent did here
myNewMethod();
}
}

Related

How to force a subClass to implement a method in superClass which has body

Class Base{
public void doThings(){
//some logic that needed by subclass
}
}
Class A extends Base{
public void doThings(){
super.doThings();
doOtherThings();
}
}
What I want is to force A to overwrite doThings() method(there will be error message if not) and call super.doThings(); but doThings() in Base should not be abstract for it has body.
Is there any decent solutions? I found the same question in below link but the accepted answer does not answer it right.
Force SubClasses to #Override method from SuperClass. Method in SuperClass must have body
If you want to make sure that doThings of the base class is called, you should design your class like this:
abstract class Base {
public void doThings() {
// do some things here
...
// make sure subclass does some things too
methodYouMustImplement();
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
// do some other things
}
}
This way, A is forced to give a implementation of methodYouMustImplement() and it is guaranteed by design that your code in doThings() is called without the need to remember to call super.doThings().
You could then consider making doThings() final, as Andy Turner suggested.
I think it would be easier to use a construct such as:
public class Base {
public void doStuff() {
doSpecificStuff();
// do base stuff every one has to do
}
abstract void doSpecificStuff();
}
public class WeirdlySpecific extends Base {
public void doSpecificStuff() {
// specific stuff happens
}
}
This does not force WeirdlySpecific to actually implement the doStuff() method, but as long as doStuff() is called as a contract by any caller, each more specific implementation has its own version of events.
A requirement to call the super method is considered an anti-pattern; that aside, the only way you can force a subclass to implement a method is to make it abstract.
If you want super.doThings() to be called first, and then subclass-specific stuff to be run after, turn the problem around:
Make doThings() final
Add an abstract method that is called within doThings().
Something like this:
abstract class Base {
public final void doThings() {
methodYouMustImplement();
// Stuff after subclass-specific implementation.
}
abstract void methodYouMustImplement();
}
class A extends Base {
#Override void methodYouMustImplement() {
doOtherThings();
}
}
The fact that doThings() is final is important to the requirements: this guarantees that the things you want to happen when doThings() is invoked, because no subclass can change this method. If you leave it non-final, subclasses can decide to override doThings(), meaning that methodYouMustImplement() (and any other actions you specify in doThing()) are not necessarily called.

Calling child constructor interlaced in parent constructor in java

I have lots of children to a base class and plan for adding a lot more. I'm lazy. The child creator sets up some basic things that is needed for the super constructor and vice versa. A simple solution from my problem would be the following:
parent {
public parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
}
child{
public child(){/*some code;*/ super.finalSetup();}
}
How ever, calling super.finalSetup() on every child is quite the hassle, and if I forget it on one it'll break. That's no good. My question is simple: is there any way to set this up form the parent. As far as my google skills go I haven't been able to find one. Hopefully you guys know something I don't.
Thanks
Consider the Factory pattern to create generic type that extends Parent.
public class Parent {
public Parent(){/*some code*/}
public void finalSetup(){/*code that dependent on the fact that the child constructor has run*/}
public static <T extends Parent> T makeChild(Class <T> klass) {
T child = null;
try {
child = klass.newInstance();
child.finalSetup();
}
catch (InstantiationException| IllegalAccessException ex) {
// somthing went wrong
}
return child;
}
}
and call
Child child = Parent.makeChild(Child.class);
It is useful when:
+ a class can't anticipate the class of objects it must create
+ a class wants its subclasses to specify the fields or objects it creates
+ classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate
This should be what you want, but as already mentioned, it can be not the best idea. You don't need to explicitly call the parent constructor in your subclass if you have a no-argument constructor in your superclass.
abstract class Parent {
Parent() {
/*some code*/
childInit();
finalSetup();
}
void finalSetup() {/*code that dependent on the fact that the child constructor has run*/}
abstract void childInit();
}
class Child extends Parent {
#Override
void childInit() {
/* the code you would put in child's constructor */
}
}
This should do it. The basic idea is to override the before and after methods in your children and in the parent constructor you simply run both and do some initialization in between. Of course this does not save you from forgetting to call the parent constructor.
abstract class Parent {
Parent(){
doBefore();
// some stuff
doAfter();
}
abstract void doBefore();
abstract void doAfter();
}
class Child extends Parent {
Child(){
super();
}
void doBefore(){
// do before stuff
}
void doAfter(){
// do after stuff
}
}
With abstract methods in your parent you can implement any permutation of before / after procedures.

calling super method from unrelated method

Today I realized that calling super.foo() is possible not only inside an overriding foo method, but also inside completely unrelated methods:
class Base
{
void foo()
{
}
}
class Derived extends Base
{
void foo()
{
}
void bar()
{
super.foo();
}
}
Is there any real-world scenario, Design Pattern or whatever where this is actually useful?
This would be helpful when a child class wants to provide more meaningful names to a method than the parent class, or providing additional information about the operation in the method name.

The meaning of 'subclasses of the containing class' in Java?

I came across the expression 'subclasses of the containing class' when I read a paper. What does that containing class mean in Java? This is the excerpt from the paper.
Primarily, this entailed three things: (i) studying the implementation of the entity, as well as its usage, to reason about the intent behind the functionality; (ii) performing static dependency analysis on the entity, and any other types, methods, or fields referenced by it, including constants; and (iii) examining the inheritance hierarchy and subclasses of the containing class. This approach took considerable time and effort to apply.
This example has a subclass of the containing class:
class Parent {
class Child {
}
}
class ParentSubclass extends Parent {
void whatever() {
new Child(); // Creates an instance of Parent.Child
}
}
ParentSubclass is a subclass of the containing class of Child. Note that outside of Parent (or its subclasses), new Child() will not work, as you need to have a containing ("outer") class to instantiate a non-static "inner" class.
Things get a bit crazy when you now add a method doSomething to Parent, invoke it in Child but override it in ParentSubclass.
class Parent {
void doSomething() {
System.out.println("Not doing anything");
}
class Child {
void whatever() {
doSomething(); // actually: Parent.this.doSomething()
}
}
}
class ParentSubclass extends Parent {
void doSomething() {
System.out.println("I'm just slacking.");
}
void whatever() {
Child a = new Child(); // Creates an instance of Parent.Child
a.whatever(); // will print "I'm just slacking".
}
}
Situations like this make static code analysis a quite hard problem.
Since I have no access to the paper, this is my best guess: in Java, classes can be related to each other in more than one way: in addition to inheriting from one another, classes can also be nested inside one another.
Here is an example of a class inheriting from the class inside which it is nested:
public class Outer {
public void doSomething() {
// ...does something
}
private static class Inner extends Outer {
public void doSomething() {
// ...does something else
}
}
}
In the example above, Inner inherits from Outer, which serves as its containing class.

Java children execute method of ancestor

There are three classes - Children, Father, and Ancestor. Children extends Father, and Father extends Ancestor, like below:
public class Ancestor {
public void test() {
}
}
public class Father extends Ancestor {
#Override
public void test() {
}
}
public class Children extends Father {
#Override
public void test() {
}
}
How I can use Ancestor's test() method in Children's test() method? I want to skip Father's test() method.
You can't. Java does not permit doing something like super.super.method(). The reasons for this are outlined in this excellent answer, but the bottom line is that it violates encapsulation.
If the functionality is really necessary, and it makes sense to do something like this, you can always add a method in your Father class that just calls the super.test() method, but doing things like this is usually bad practice. Unless you have some really good reasoning, rethink your code. There shouldn't really be any necessity to call a method from either this nor super.
The short answer is, you can't. It violates encapsulation and is generally bad practice. A better way to accomplish what you want would be to make Ancestor.test() abstract and have a new protected method like Ancestor.baseTest(); Then, you could call Ancestor.baseTest() from Father, Child and any other subclass that wants to access the logic.

Categories