Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does java support "Soft" interfaces?

Consider the following scenario: Say that you created an interface Foo:

public interface Foo {

    public void bar();

}

And say that there is an old class SomeOldClass in a certain library that you want to use. It already has the bar() method, but does not explicitly implement Foo.

You have written the following code for all classed that implement Foo:

public <T extends Foo> T callBarOnThird(List<T> fooList){
    return fooList.get(2).bar();
}

And now you want it to also work for SomeOldClass. You dont have access to the source code of this class, so you can't modify it.

Is there a way to declare Foo or something similar as some sort of "soft" interface, (as in where any class that implements all the required methods would be accepted as an implicit implementation of the soft interface)? If not, how would you solve this with code that is as clean as possible?

like image 275
Rik Schaaf Avatar asked Sep 27 '18 07:09

Rik Schaaf


People also ask

Is interface supported in Java?

2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).

Which interface does Java use?

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables.

Does Java support multiple inheritance?

The Java programming language supports multiple inheritance of type, which is the ability of a class to implement more than one interface. An object can have multiple types: the type of its own class and the types of all the interfaces that the class implements.

Is interface in Java polymorphism?

This is an example of polymorphism, which is method overloading. Types of polymorphism in Java: Run time polymorphism. Compile-time polymorphism.


1 Answers

No, it does not.

You have to provide an adapter instance (there are several methods and tools to help with that, but Java does not do it "implicitly").

like image 183
Thilo Avatar answered Oct 06 '22 21:10

Thilo