I have class Dad with subclass Son. I'd like to create a subclass of Dad and a subclass of Son that overrides a method of Dad.
What would be the best way of doing this without repeating code? I can not modify Dad and Son.
Given...
public class Dad {
public void doSomething() {}
}
public class Son extends Dad {
}
...I'd like to create...
public class DadSubclass extends Dad {
#Overrides
public void doSomething() {
// My code
}
}
public class SonSubclass extends Son {
#Overrides
public void doSomething() {
// My code
}
}
...without repeating // My code.
The obvious solution would be to create a helper class and call it for both, but this is problematic if I want to call protected methods, and I'm not allowed to create the subclasses with the same package.
Is there a better solution?
Create a common helper class and call it.
Assuming your code isn't accessing member variables, I would just put this code in a static utility class. If this isn't the case, you can still do this by passing in a common superclass - that of 'Dad' public static void mycode(Dad d). If you need specific variables in the subclasses themselves, I would rethink your class structure.
What you really want here is something like this:
class DadSonSubclass extends Dad, Son {
public void doSomething() {
//mycode
}
}
This is multiple inheritance, which is not supported by Java. So your only option would be to create a helper/utility class, which is perfectly acceptable. If you need to call protected methods, just pass the Dad object in to the helper class and create public callback methods to access this info.
Maybe better, maybe not, depending on your point of view, but it can certainly be done. Put your code into a helper class, and use a callback to give that helper access to the protected methods it needs:
interface Callback {
void foo();
void bar();
void one();
void two();
}
class Helper {
static void helpMe(Callback callback) {
// My code
}
}
class DadSubclass extends Dad {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
DadSubclass.this.foo();
}
public void bar() {
DadSubclass.this.bar();
}
public void one() {
throw new UnsupportedOperationException("one() doesn't exist in Dad");
}
public void two() {
throw new UnsupportedOperationException("two() doesn't exist in Dad");
}
});
}
}
class SonSubclass extends Son {
#Override
public void doSomething() {
Helper.helpMe(new Callback() {
public void foo() {
SonSubclass.this.foo();
}
public void bar() {
SonSubclass.this.bar();
}
public void one() {
SonSubclass.this.one();
}
public void two() {
SonSubclass.this.two();
}
});
}
}
Related
I am trying to find the most elegant way to allow a child and parent to react to an event initiated by the grandparent. Here's a naive solution to this:
abstract class A {
final public void foo() {
// Some stuff here
onFoo();
}
protected abstract void onFoo();
}
abstract class B extends A {
#Override
final protected void onFoo() {
// More stuff here
onOnFoo();
}
protected abstract void onOnFoo();
}
class C extends B {
#Override
protected void onOnFoo() {
// Even more stuff here
}
}
So basically, I'm trying to find the best way to allow all related classes to perform some logic when foo() is called. For stability and simplicity purposes I prefer if it is all done in order, although it's not a requirement.
One other solution I found involves storing all the event handlers as some form of Runnable:
abstract class A {
private ArrayList<Runnable> fooHandlers = new ArrayList<>();
final public void foo() {
// Some stuff here
for(Runnable handler : fooHandlers) handler.run();
}
final protected void addFooHandler(Runnable handler) {
fooHandlers.add(handler);
}
}
abstract class B extends A {
public B() {
addFooHandler(this::onFoo);
}
private void onFoo() {
// Stuff
}
}
class C extends B {
public C() {
addFooHandler(this::onFoo);
}
private void onFoo() {
// More stuff
}
}
This method is certainly preferable to the first. However I am still curious if there is a better option.
Have you considered the Template Method pattern? It works well to define a high level method that delegates to derived types to fill-in the gaps.
What about this by calling the super method?
class A {
void foo() {
System.out.println("Some stuff here");
}
}
class B extends A {
#Override
void foo() {
super.foo();
System.out.println("More stuff here");
}
}
class C extends B {
#Override
void foo() {
super.foo();
System.out.println("Even more stuff here");
}
}
I have an abstract class Task with two methods execute() and finish() as the following:
abstract class Task {
abstract void execute();
private void finish() {
// Do something...
}
}
How can I ensure that the overloaded method execute() in subclasses of Task implicitly calls finish() as the last statement?
I don't believe there is any way of 'forcing' sub-classes to invoke a method but you could try some sort of template method approach:
abstract class Foo {
protected abstract void bar(); // <--- Note protected so only visible to this and sub-classes
private void qux() {
// Do something...
}
// This is the `public` template API, you might want this to be final
public final void method() {
bar();
qux();
}
}
The public method is the entry-point and invokes the abstract bar and then the private qux method, this means that any sub-classes follow the template pattern. However it's no panacea of course - a sub-class could simply ignore the public method.
You can create a ExecutorCloseable class that implements the [AutoCloseable] interface, such as:
public class ExecutorCloseable extends Foo implements AutoCloseable
{
#Override
public void execute()
{
// ...
}
#Override //this one comes from AutoCloseable
public void close() //<--will be called after execute is finished
{
super.finish();
}
}
You could call it this way (silly main() example):
public static void main(String[] args)
{
try (ExecutorCloseable ec = new ExecutorCloseable ())
{
ec.execute();
} catch(Exception e){
//...
} finally {
//...
}
}
Hope it makes sense, I can't really know how you call these methods nor how you create the classes. But hey, it's a try : )
For this to work, the finish() method on Foo should be protected or public (first one recommended), though.
I am not sure how am I suppose to go about my question. It is about Android can Instantiate Interface. I am trying to do in C#. Now I am pretty sure that the rules for both Java and C# is you can't create an Instance of abstract and Interface as being said.
But I would really like to know how Android does this practice.
In Android you can do this.
public interface Checkme{
void Test();
void Test2();
}
public void myFunc(Checkme my){
//do something
}
// Now this is the actual usage.
public void Start(){
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
}
Actually once you press Enter on new Checkme() You will automatically get the Override methods of the Interface. Like auto Implement method of an Interface in C#.
I hope my question make sense.
C# doesn't support anonymously auto-implemented interfaces because it has delegates:
public void Foo(Func<string> func, Action action) {}
// call it somewhere:
instance.Foo(() => "hello world", () => Console.WriteLine("hello world"));
With delegates you can fill the gap and it can be even more powerful than implementing interfaces with anonymous classes.
Learn more about delegates.
This is an Anonymous Class:
public void Start(){
myFunc(new Checkme() {
#Override
public void Test() {
}
#Override
public void Test2() {
}
});
}
An anonymous class is an unnamed class implemented inline.
You could also have done it using a Local Class, but those are rarely seen in the wild.
public void Start(){
class LocalCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
myFunc(new LocalCheckme());
}
These both have the advantage that they can use method parameters and variables directly, as long as they are (effectively) final.
As a third option, you could do it with an Inner Class.
private class InnerCheckme implements Checkme {
#Override
public void Test() {
}
#Override
public void Test2() {
}
}
public void Start(){
myFunc(new InnerCheckme());
}
An inner class cannot access method variables (obviously because it's outside the method), but can be used by multiple methods.
Any local values from the method can however be passed into the constructor and stored as fields of the inner class, to get the same behavior. Just requires a bit more code.
If the inner class doesn't need access to fields of the outer class, it can be declared static, making it a Static Nested Class.
So, all 3 ways above a very similar. The first two are just Java shorthands for the third, i.e. syntactic sugar implemented by the compiler.
C# can do the third one, so just do it that way for C#.
Of course, if the interface only has one method, using a Java lambda or C# delegate is much easier than Anonymous / Local / Inner classes.
If I understand correcly, you're defining a class that implements an interface, and when you specify that the class implements an interface, you want it to automatically add the interface's methods and properties.
If you've declared this:
public interface ISomeInterface
{
void DoSomething();
}
And then you add a class:
public class MyClass : ISomeInterface // <-- right-click
{
}
Right-click on the interface and Visual Studio will give you an option to implement the interface, and it will add all the interface's members to the class.
you mean something like this?
pulic interface Foo{
void DoSomething();
}
public class Bar : Foo {
public void DoSomething () {
//logic here
}
}
myFunc(new Checkme(){
#Override
public void Test()
{
}
#Override
public void Test2()
{
}
});
You're passing into myFunc() something that is called an anonymous class. When it says "new Checkme() { .... }", it is defining an anonymous implementation of the Checkme interface. So, it's not an instance of the interface itself, just an instance of a type that implements it.
In C# anonymously implemented classes for Interface are not auto generated just like in java, you need to follow the below procedure to workout.
public class MyClass {
public void someMethod (string id, IMyInterface _iMyInterface) {
string someResponse = "RESPONSE FOR " + id;
_iMyInterface.InterfaceResponse (someResponse);
}
}
public interface IMyInterface {
void InterfaceResponse (object data);
void InterfaceResponse2 (object data, string x);
}
public class MyInterfaceImplementor : IMyInterface {
private readonly Action<object> actionname;
private readonly Action<object, string> actionInterfaceResponse2;
public MyInterfaceImplementor (Action<object> InterfaceResponse) {
this.actionname = InterfaceResponse;
}
public MyInterfaceImplementor(Action<object> interfaceResponseMethod, Action<object, string> interfaceResponseMethod1) {
this.actionname = interfaceResponseMethod ?? throw new ArgumentNullException(nameof(interfaceResponseMethod));
this.actionInterfaceResponse2 = interfaceResponseMethod1 ?? throw new ArgumentNullException(nameof(interfaceResponseMethod1));
}
public void InterfaceResponse (object data) {
this.actionname (data);
}
public void InterfaceResponse2(object data, string x) {
this.actionInterfaceResponse2(data, x);
}
}
Gist Source : https://gist.github.com/pishangujeniya/4398db8b9374b081b0670ce746f34cbc
Reference :
I have a couple of helper classes (? extends HelperBase) which only have public static methods. I would like to have something similar to what a factory is (with singleton support), but as there is no need for an instance, I am unsure which way to go best.
In the end, I would like to have something like:
enum HELPER_TYPE {
Type_A
}
abstract class HelperBase {
abstract void do();
static HelperBase getHelper(HELPER_TYPE type) {
// ...
}
}
class Helper1 extends HelperBase {
static void doImpl() {
// ... impl here
}
void do() {
doImpl();
}
}
// ... and then:
HelperBase helper = HelperBase.getHelper(HELPER_TYPE.Type_A);
helper.do();
Is there a better way ? Any suggestion would be appreciated.
enum HELPER_TYPE implements IHelper{
Type_A{
#Override
public void doSomething(){
}
},
Type_B{
#Override
public void doSomething(){
}
}
}
interface IHelper{
public void doSomething();
}
How about having an interface with required methods and having enum implement that?
Now you have polymorphic behavior among all helpers implementing IHelper interface.
So you can call them like HELPER_TYPE.Type_A.doSomething()
Having this tasteful class
public abstract class CakeSkill
{
//..
boolean cherry=false;
private void finalMandatoryTouch()
{
cherry=true;
}
abstract public void cook();
}
A class that extends it would be something like
class Cheff extends CakeSkill
{
//..
void cook()
{
//..Secret recipe
}
}
But of course this won't work,
finalMandaroryTouch() hasn't been called, then no cake will end with a cherry..
[EDIT]
This one could be a solution
class MemoriousCheff extends CakeSkill
{
//..
void cook()
{
//..Secret recipe
finalMandatoryTouch();
}
}
but requires :
Cheff to have a perfect memory that don't forget to call finalMandatoryTouch()
Making finalMandatoryTouch() to be protected (at least)
[/EDIT]
It would be great! (but no Java) if something like this could be done
abstract public void cook()
{
#implementedMethod
finalMandatoryTouch();
}
How can be implemented this useful functionality ?
Thank you very much
Change cook to a protected method cookImpl then have a public final method called cook:
public final void cook()
{
cookImpl();
finalMandatoryTouch();
}
protected abstract void cookImpl();
That way the subclass only needs to worry about cookImpl, but callers of cook get the cherry on top. Callers not in the same package or class hierarchy won't even see cookImpl, so won't be able to call it directly.
This is the template method pattern, basically.
It's called the Template method pattern.
final public void cook() {
mainCookRecipe();
finalMandatoryTouch();
}
abstract public void mainCookRecipe();
public abstract class CakeSkill {
public void cook() {
doCook();
finalMandatoryTouch();
}
protected abstract doCook();
private finalMandatoryTouch() { ... }
}
Etc.
You could change your cook() method to an actual method and then invoke a separate abstract method as well as your finalMandatoryTouch() method.
In your abstract class:
public void cook() {
specificCook();
finalMandatoryTouch();
}
abstract void specificCook();
It seems that inheritance is not the right way to model your problem. In Java you can only inherit from one class, and since it's also a very static relationship, it limits your chef in the skills he can perform.
A better way would be to use composition. Cooking skills could be strategies that the chef performs:
interface CookingSkill {
void cook();
}
class CakeSkill implements CookingSkill {
private boolean cherry = false;
private void finalMandatoryTouch() {
cherry = true;
}
public void cook() {
//...
finalMandatoryTouch();
}
}
class Chef {
private CookingSkill cookingSkill;
// getters and setters ...
public void cook() {
// ...
cookingSkill.cook();
// ...
}
}
Now you can assign different cooking skills to your chef.