Reputation: 359
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 ?
Upvotes: 3
Views: 124
Reputation: 4372
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
Upvotes: 1
Reputation: 1851
If you want to do this in spring, the general idea would be:
// Test.java
public class Test {
private final Interface1 i1;
private final Interface2 i2;
public Test(Interface1 i1, Interface2 i2) {
this.i1 = i1;
this.i2 = i2;
}
}
<!-- application-context.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="implementer" class="org.mypackage.Implementer" />
<bean id="test" class="org.mypackage.Test">
<constructor-arg ref="implementer"/>
<constructor-arg ref="implementer"/>
</bean>
</beans>
// Main.java
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
Test t = (Test) context.getBean("test");
}
Upvotes: 0
Reputation: 37645
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.
Upvotes: 3