Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 725
Jim Avatar asked Jul 25 '14 07:07

Jim


3 Answers

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.

like image 61
gexicide Avatar answered Oct 17 '22 12:10

gexicide


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(){

        }
    }
like image 1
Seb Avatar answered Oct 17 '22 11:10

Seb


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 {

}
like image 1
Oliver Watkins Avatar answered Oct 17 '22 13:10

Oliver Watkins