Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java 7 alternative to default methods in interface (only in Java 8)

Tags:

java

I wanted to use default methods in one of my interface classes - then I realised that this is only available in Java 8 - and we are using Java 7.

What is the best way of achieving similar in Java 7 ?

like image 423
NottmTony Avatar asked Jun 10 '16 09:06

NottmTony


People also ask

Can we override default method in java interface 8?

A default method cannot override a method from java.

Can we override default and static method of interface in Java 8?

Static method in interface are part of the interface class can't implement or override it whereas class can override the default method.

What is the use of default method in interface in Java 8?

Java 8 introduces a new concept of default method implementation in interfaces. This capability is added for backward compatibility so that old interfaces can be used to leverage the lambda expression capability of Java 8. For example, 'List' or 'Collection' interfaces do not have 'forEach' method declaration.

What are the methods java 8 interface can have?

Prior to java 8, interface in java can only have abstract methods. All the methods of interfaces are public & abstract by default. Java 8 allows the interfaces to have default and static methods.


1 Answers

Have your methods signature in an interface, as in Java 8.
Have your method default implementation in an abstract class implementing that interface.
Have your method final implementation in a class extending that abstract class.

Now you have to be aware that it will still not be the same as having Java 8's interfaces' default method, in particular because you cannot extend multiple abstract class, while you can implement multiple interfaces with their default methods.

like image 92
Aaron Avatar answered Sep 23 '22 07:09

Aaron