Re: Query regarding java Multiple Inheritance
Amit Jain wrote:
Hi All,
I am new to Java and need your views for my query.
What will be the solution for implementint two Interface in a single
class A if these interfaces I1 and I2 are written as mentioned below:
interface I1{
void method ();
long square(long i);
}
interface I2{
String method();
long squareRoot(long i);
}
class A implements I1, I2{
void method(){
System.out.println("--- Hi ----");
}
// implementation of square() and squareRoot() method
}
Above implementation of interface in class A will never complies
because of "void method();" declared in both I1 and I2. And we want
the implementation of I1 and I2 in class A only. How can we acheive
this in such situations.
Java does not allow this construct. You need a workaround.
I once created the example below to illustrate a
possible workaround which I believe is a reasonable good
one.
Arne
========================
public class MultiInterf {
public static void main(String[] args) {
A o = new A();
System.out.println(o.asB().f());
System.out.println(o.asC().f());
}
}
interface B {
Object f();
}
interface C {
boolean f();
}
class A {
public Object fB() {
return null;
}
public boolean fC() {
return false;
}
public B asB() {
return new AB(this);
}
public C asC() {
return new AC(this);
}
private static class AB implements B {
private A real;
public AB(A real) {
this.real = real;
}
public Object f() {
return real.fB();
}
}
private static class AC implements C {
private A real;
public AC(A real) {
this.real = real;
}
public boolean f() {
return real.fC();
}
}
}