How do you implement multiple inheritance in JAVA?
A1- First of all, Java doesn't allow you to have one class extending 2 or more classes. According to the problem you are dealing with, you can have your class to extend another class and implement many interfaces.
But let's say that you have 2 classes A and B already implemented from a library and you want the class C to "extend from both". What can you do?
The solution A1 doesn't apply to this problem. So let's see other options:
A2- You can extend one class (e.g. C extends A) and write on your class C all non-private members from class B, redirecting them to class B members. E.g:
public class A{
//...
}
public class B{
public int bMehtod(int param) { return (param + 123); }
}
public class C extends A{
private B b;
public C() { this( new B() ); }
public C(B b) {
if ( b==null ){
this.b = new B();
} else {
this.b = b;
}
}
//B members section
public int bMehtod(int param) {
return this.b.bMehtod(param); //just forward the call to B
}
}
No comments:
Post a Comment
Please, before starting to comment, evaluate if what you want to write is useful, respectful and positive. A kid may read this also.
Give a good example!