With java 8, you can define default implementation of a method inside the interface.
public interface A {
default void method1() { System.out.println("Default method1 implementation"); }
void method2();
void method3();
}
Question
Suppose I have an interface which has 3 methods. This interface is to be implemented by many classes but the implementation of say method1 will be same in all classes.
I can make an abstract class and give a concrete implementation for method1 and let my classes extend this class.
My question is when I am already extending a class, how do I also extend this abstract class. Java doesn't support it. How should I design in such a scenario?
interface Inf{
void method1();
void method2();
void method3();
}
public abstract class Abs implements Inf{
void method1(){
//concrete implementation
}
}
class Test extends SomeClass implements Inf{
//here I need method1 implementation and other methods Ill implement
}
class SomeClass{
}
Solution
With java 8, you can define default implementation of a method inside the interface.
public interface A {
default void method1() { System.out.println("Default method1 implementation"); }
void method2();
void method3();
}
OTHER TIPS
Java doesn't support Multiple Inheritance
. i.e A Class cannot have more than one Base class. What you can do is make the SomeClass
to extend Abs
class
class SomeClass extends Abs{
}
class Test extends SomeClass implements Inf{
//here you can get method1 implementation since Someclass extends Abs
}
Note : As said by @anonymous , you can make use of default methods
of interface
if you work in Java 8
Java doesn't support multiple inheritance. You can make your Abs class to extend SomeClass
class Abs extends SomeClass {
}
class Test extends Abs implements Inf {
}