Reputation: 29877
I have a method that gets overridden and in this method super is used to call the method that is overridden. The code within this method however is something I use in several classes and I want to therefore reuse this code by putting it into a single method in just one class. But since this code uses the keyword super, I am not sure how to pass a reference of the overridden method to my new method. For example, here is the original method inc class1:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
/* Lots of code goes here, followed by the super call */
return super.onOptionsItemSelected(item);
}
In class2:
public boolean onOptionsItemSelected(MenuItem item)
{
/* Code from class1 gets relocated here. But how do I call super on the original method? */
}
Upvotes: 0
Views: 230
Reputation: 4205
You could simply make Class2 extend the same class as Class1.
The rest of this answer assumes that Class1 does not inherit from Class2.
Without further context, it's hard to say whether this is appropriate, but you could try changing
public boolean onOptionsItemSelected(MenuItem item)
to
public static boolean onOptionsItemSelected(MenuItem item)
, and call
YourClassName.onOptionsItemSelected(yourArgument)
Upvotes: 0
Reputation: 78639
Well, unless class 2 is a common ancestor of your class 1, you can't invoke it with super. If you moved your code to another class not related by inheritance you would be forced to use object composition, that is, your class 1 (where super invocation resides today) will need an object reference to a class 2 (where code has been move to) object in order to gain access to the given method.
public boolean onOptionsItemSelected(MenuItem item)
{
/* Lots of code goes here, followed by the super call */
return this.myRef.onOptionsItemSelected(item);
}
Alternatively, you could make the method in question static, in whose case you could gain access to it through the class exposing it (let's say it's called Util).
public boolean onOptionsItemSelected(MenuItem item)
{
/* Lots of code goes here, followed by the super call */
return Util.onOptionsItemSelected(item);
}
Depending on what the method does, though, making it static may not be an option.
Upvotes: 1