i have 2 interfaces inter1 and inter2 and class that implements both of them:
public interface Interface1 {
method1();
}
public interface Interface2 {
method2();
}
public class Implementer implements Interface1, Interface2 {
method1() {
// something
}
method2() {
// something
}
}
public class Test {
public static void main(String[] args) {
Interface1 obj = quest();
obj.method1();
if(obj instanceof Interface2) {
obj.method2(); //exception
}
}
public static Interface1 quest() {
return new cl();
}
}
How to cast obj to Interface2 and call method2() or it is possible to call method2() without casting ?
If you write inter1 obj = ... then you will not be able to write obj.method2) unless you cast to inter2 or to a type that implements inter2.
For example
inter1 obj = quest();
if (obj instanceof class1)
((class1) obj).method2();
or
inter1 obj = quest();
if (obj instanceof inter2)
((inter2) obj).method2();
As an aside, when you write in Java you normally give classes and interfaces names that begin the a capital letter, otherwise you confuse people reading your code.
Using genecics it is possible to declare generic reference implementing more than one type. You can invoke method from each interface it implements without casting. Example below:
public class TestTwoTypes{
public static void main(String[] args) {
testTwoTypes();
}
static <T extends Type1 & Type2> void testTwoTypes(){
T twoTypes = createTwoTypesImplementation();
twoTypes.method1();
twoTypes.method2();
}
static <T extends Type1 & Type2> T createTwoTypesImplementation(){
return (T) new Type1AndType2Implementation();
}
}
interface Type1{
void method1();
}
interface Type2{
void method2();
}
class Type1AndType2Implementation implements Type1, Type2{
@Override
public void method1() {
System.out.println("method1");
}
@Override
public void method2() {
System.out.println("method2");
}
}
The output is:
method1
method2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With