Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial implementation of an interface

Tags:

java

Having only a small amount of time to search for such things, I could not see anything that covered my specific scenario.

I am working with a 3rd party interface. Let us say for a moment it is as follows:

    public interface interface1
    {
        public String getVar1();

        public void  method1();

        public void method2();

    }

I need to create a number of classes that make use of this interface but the actual method implementation of "method2" would differ on each,where as "method1" and "getVar1" would always be the same code.

Is there any way to create an abstract base class that implements the interface but only forces the implementation of "method2" onto the child classes?

I had tried

public abstract @Override void method2

but while this is "acceptable" at design time in Netbeans (don't know if Eclipse acts differently) at compile time it complains that method2 needs to be implemented.

If it is not possible, fair enough, I just need to check.

thanks

like image 643
Paul Eden Avatar asked Sep 03 '13 10:09

Paul Eden


Video Answer


2 Answers

You can do this by creating an abstract class that implements the interface. Any sub-class of this abstract class will be required to implement any interface methods that were not yet defined.

public abstract class AbstractInterface implements interface1 {
    @Override
    public String getVar1() {

    }

    @Override
    public void method1() {

    }
}
public class Implementation extends AbstractInterface {
    @Override
    public void method2() {

    }
}

See: Java tutorial on abstract classes.

like image 132
Tim Cooper Avatar answered Oct 05 '22 15:10

Tim Cooper


You can create an abstract class which does not implement method2()

public abstract class AbstractImplementation implements interface1 {
    public String getVar1() { 
      // implementation ..
    }

    public void  method1() {
      // implementation ..
    }

    // skip method2
}

Then create multiple implementations:

public class Implementation1 extends AbstractImplementation {
    public void method2() {
      // implementation 1
    }
} 

public class Implementation2 extends AbstractImplementation {
    public void method2() {
      // implementation 2
    }
}

...
like image 42
micha Avatar answered Oct 05 '22 17:10

micha