R
R
reus2017-04-18 13:28:34
Java
reus, 2017-04-18 13:28:34

Passing to the constructor of any object?

A question. How to write constructor arguments so that any object that implements the desired interface is accepted?
in theory it should be something like this

public MyClass(<? extends MyInterface> obj){
...
}

But that doesn't work. How to implement it correctly in java?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Oparin, 2017-04-18
@losse_narmo

public MyClass(MyInterface obj){
...
}

D
davidnum95, 2017-04-18
@davidnum95

It is possible like this:

public <T extends SomeInterface> MyClass(T object) {
}

D
Dmitry Alexandrov, 2017-04-18
@jamakasi666

This is called generics.

class MyClass<T extends MyInterface>{
private T val;
public MyClass(T obj){
val= obj;
...
}
}

In your situation, you can do something like this:
public MyClass(MyInterface obj){
...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question