Using composition over inheritance when overriding - java

If I have a class that I would like to customise by overriding one if its methods the only I can do this is by using inheritance (sub-classing and overriding method) ? Is it possible to use composition in some way to achieve same goal ?

Yes, you can use delegation. Instead of deriving from Foo in the example below, Bar contains a Foo and delegates to it where it chooses.
interface SomeMethods {
void doSomething();
void doSomethingElse();
}
class Foo implements SomeMethod {
public void doSomething() { // implementation }
public void doSomethingElse() { // implementation }
}
class Bar implements SomeMethod {
private final Foo foo = new Foo();
public void doSomething() { foo.doSomething(); }
public void doSomethingElse() { // do something else! }
}

Using composition instead of inheritance is a design choice.
Either your class has been designed with inheritance in mind (i.e. it provides non-final public and protected methods, intended to be overridden by subclasses), or it has been designed with composition or delegation in mind (by using the strategy pattern, for example).
If the class has not been designed for customization at all, you might be able to customize it using inheritance, but not using a composition/delegation mechanism.

Sure. You can use the following patterns.
Simple overriding of method method
Template method pattern
class Base {
public void foo() {
// do something
bar();
// do something
}
protected abstract void bar();
}
class Child {
protected void bar() {
// do something.
}
}
Delegation
class Base {
private Runnable r;
protected Base(Runnable r) {
this.r = r;
}
public void foo() {
r.run();
}
}
class Child extends Base {
Child() {
super(new Runnable() { /* implementation */})
}
}

Related

prevent explicit invocation of an overridable method (Java)

I have a number of classes that define a method, and I want to execute some code (say, some "prologue" and "epilogue") around that method:
public interface Thing {
public void stuff();
public void callStuff();
}
public abstract class Something implements Thing {
public abstract void stuff();
public void callStuff() {
... // common prologue
//try {
stuff();
//} finally {
... // common epilogue
//}
}
}
public class A extends Something {
public void stuff() { ... }
}
public class B extends Something {
public void stuff() { ... }
}
public class Wrapper extends Thing {
private Thing t;
Wrapper(Thing thing) { t = thing; }
public void stuff() { t.stuff(); }
public void callStuff() { t.callStuff(); }
}
// Use:
Something s = ...;
s.callStuff();
You see that the idea is that subclasses will redefine stuff() while the clients will invoke callStuff(). Nevertheless, in some rare cases one has to call stuff(), see Wrapper above.
Something like that we see in the Thread class (since JDK 1.0), child classes redefine run() but the clients invoke start().
How do I prevent clients from calling stuff() directly?
EDIT
protected does not work here because the "clients" really are children of Something coded by another team. #Deprecated would work, but stuff() is not really deprecated, and everyone knows what "deprecated" is, so I cannot redefine the meaning of #Deprecated.
Ideally, the compilation should fail unless an explicit directive is given to ignore the problem.

C# equivalent to implement interface inside super keyword in Java [duplicate]

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 :

Subclassing an enum value

I want to be able to subclass some values in an enum, in order that I don't have to repeat code too much. Is there some way I can do this? Here's an example of what I want to achieve, which Eclipse quickly tells me is an abomination:
public enum Foo {
BAR {
#Override
public void taskA() {
System.out.println("A");
}
#Override
public void taskB() {}
},
BAZ extends BAR {
#Override
public void taskB() {
System.out.println("B");
}
};
public abstract void taskA();
public abstract void taskB();
}
BAR would have only the implementation of taskA and an empty taskB, and BAZ would have both methods - BAR's implementation of taskA, and its own implementation of taskB.
I'm not changing the values of the enum after it's declared, so why doesn't this work? I could call BAR's taskA method within BAZ, so why can't I do this?
I want to be able to subclass some values in an enum, in order that I
don't have to repeat code too much.
The usual way to share code among constant-specific methods is to declare a private static method (either in the enum itself or in a utility helper class) which contains the common code that you wish to access from your constant-specific methods.
For example ...
public enum Foo {
BAR {
#Override
public void taskA() {
commonToTaskAandB();
System.out.println("B");
}
#Override
public void taskB() {}
},
BAZ {
#Override
public void taskB() {
commonToTaskAandB();
System.out.println("B");
}
};
public abstract void taskA();
public abstract void taskB();
private static void commonToTaskAandB() {
// shared code here
:
:
}
}
Note that the code "BAZ extends Bar" is illegal because BAZ is not a type. BAZ is an instance of your Enum<Foo> type. An instance cannot extend another type. It is incorrect to apply object-oriented principles like inheritance to enum constants because, in Java, enum constants are instances of a class and not classes themselves.
Enum-Constants are objects (instances), not classes. You can only subclass classes.
However even that will not work: you can only extend enums with anynomous inner classes.
You will have to find another solution for your use case. You could:
use a static method for the shared code
call BAR.taskA() in BAZ
make taskA not abstract and put your code there
use normal constants, instead of enums
But my favorit is:
inject behaviour instead of overriding!
Example code:
class Behavior {
public static Runnable A = new Runnable() {
public void run() {
System.out.println("A");
}
}
public static Runnable B = new Runnable() {
public void run() {
System.out.println("B");
}
}
public static Runnable DO_NOTHING = new Runnable() {
public void run() {
}
}
}
public enum Foo {
BAR(Behavior.A, Behavior.DO_NOTHING),
BAZ(Behavior.A, Behavior.B);
private final Runnable mechanismA;
private final Runnable mechanismB;
private Foo(Runnable mechanismA, Runnable mechanismB) {
this.mechanismA = mechanismA;
this.mechanismB = mechanismB;
}
public void taskA() {
mechanismA.run;
}
public void taskB() {
mechanismB.run;
}
}
Pros of this solution:
The code explicitly defines the behavior of each enum constant - no implicit calculations => easier to read
You can use inheritance, etc in the Behavior-class
You can easily switch behaviorA and behaviorB - or reuse that code anywhere else
If you have Java8 available you can even shorten the code to this:
public static Runnable A = () -> {
System.out.println("A");
};

implement an abstract method in derived class as static

I have these 2 classes
class A {
public void foo1() {
...;
foo2();
...;
}
protected abstract foo2();
}
class B extends A {
public foo2() {
......
}
I need foo2 to be static so I can do B.foo2() but I also want the functionality in class A to remain.n
Any suggestions?
}
You can't override static methods or implement abstract methods as static.
Static methods are defined on a class definition, not on a class instance. Abstract methods are defined on a class instance.
What you said doesn't make sense in fact.
Although I don't quite get why you need to do it, there is a workaround:
class B {
#Override
public void foo() {
fooUtil();
}
public static void fooUtil() {
// your impl here
}
}
Then you can do B.fooUtil() instead, and using its behavior to override A.foo().

How do you deal when the implementation for an interface method is the same for some classes?

Assume I have defined interface ISomeInterface with methods foo and bar.
E.g.
public interface ISomeInterface {
public void foo();
public void bar();
}
Let's say I have classes A and B that for them it makes sense to both implement the interface. But it also does not make sense to have a different implementation for foo().
Taking into account that deriving A from B or B from A is incorrect/weird is there a standard coding practice for this design?
I assume I could create some utilities class to implement foo() and call it as a delegate but I was wondering if this whole structure can be dealt with differently
Update:
To give a full understanding of my question I stumbled upon this:http://perlbuzz.com/2010/07/why-roles-in-perl-are-awesome.html and I was trying to understand if this feature is lacking from the traditional OO concepts as we use them in Java or not
Your edit suggests that your true question is: "Is there an equivalent for Perl roles in Java?"
Since Java 8 introduced default methods in interfaces, interfaces with default methods seem like a very good equivalent for roles. Especially, you can do what you want in your example: Provide a default implementation for foo():
interface ISomeInterface {
public default void foo(){ /* your default impl goes here */}
public void bar(); // Abstract, must be implemented by subclasses
}
class A implements ISomeInterface {
// must only implement bar, can reuse foo's default impl
}
class B implements ISomeInterface {
// must only implement bar, can reuse foo's default impl
}
If there is a feature about roles I am missing please let me know. Otherwise, I think Java8 interfaces are a quite good surrogate for roles.
Decided to turn my comment into an answer:
You could use an abstract class rather than an interface:
public abstract class FooBar {
public void foo(){
//your implementation goes here
}
abstract void bar();
}
public class A extends FooBar{
#Override
public void bar(){
}
}
Why not something like this :
public class abstract SomeAbstractClass {
public void foo(){
//implementation
}
public abstract void bar();
}
class A extends SomeAbstractClass {
}
class B extends SomeAbstractClass {
}
public abstract class SomeClass implements ISomeInterface {
public void foo() {
// I do stuff..
}
}
public class A extends SomeClass {
public void bar() {
// A specific impl. of bar..
}
}
public class B extends SomeClass {
public void bar() {
// B specific impl. of bar..
}
}
Alternatively, if you don't want A and B to be tied up by extending an abstract class you can just use composition. This also provides the flexibility to change the IFoo behaviour at run time if you were to inject the FooImpl as part of the constructor. In this example I have just hard wired the FooImpl for brevity.
public class B implements ISomeInterface {
private IFoo foo = new FooImpl();
public void foo() {
foo.doSomethingFooey();
}
public void bar() {
// B specific implementation
}
}
public class A implements ISomeInterface {
private IFoo foo = new FooImpl();
public void foo() {
foo.doSomethingFooey();
}
public void bar() {
// A specific implementation
}
}

Categories