monakons monakons - 2 years ago 73
Java Question

Define and execute partial functions of an interface

I am new to Java so i have some obvious (to some of you) questions about declaration, definition and execution of some functions.

Suppose you have declared two methods in an interface and you want to define the behavior of the first function in a (abstract?) class and the second function in another (abstract?) class.

Is there a way to define two methods in two separate classes? For example i could have a lot of methods in an interface but I want to implement just one of them because a specific object does not needs the others. How can I do that??

Java Code example :

interface DeclareFcnts {
void foo1();
void foo2();

abstract class Define_fcn1 implements DeclareFcnts {
public void foo1() {
// TODO Auto-generated method stub

abstract class Define_fcn2 implements DeclareFcnts {
public void foo2() {
// TODO Auto-generated method stub

class Myclass {
public static void main(String args[]) {
// How can i create an object that reference to the first function only?

Answer Source

If you implement an interface in a class, you must assume it will have all the interface methods declared. You must define what happens if any of these methods are invoked. Consider this:

DeclareFcnts instance = new Define_fcn1();
instance.foo2(); // what happens here?

What is your expected behavior on the second line? It could throw an exception, do nothing, (or return a value if the method wasn't void).

One option is to define the behavior in the concrete implementing class (because you cannot instantiate abstract classes), which is what you would like to avoid. Fortunatelly, in Java 8, there is another way - using default methods:

interface DeclareFcnts {
    default void foo1() { /* default implementation, e.g. throw or do nothing */ }
    default void foo2() { /* default implementation, e.g. throw or do nothing */ }

class Define_fcn1 implements DeclareFcnts {
    public void foo1() { /* do something */ }

In this case, Define_fcn1 will inherit implementation of foo2 from DeclareFcnts much like if it inherited from a super class. You can notice that the class no longer needs to be abstract.

That said, you should try to avoid such situations. They will make unit testing, refactoring, etc., more difficult. You may possibly split your interface into multiple interfaces. If you need both methods somewhere, you can pass the interfaces separately, or, if absolutely necessary, define another interface like this:

interface Foo1Iface { void foo1(); }
interface Foo2Iface { void foo2(); }
interface BothIface extends Foo1Iface, Foo2Iface {  } 

I would avoid it if possible, though. You may get more suggestions if you add more details to your answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download