Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

Friday, February 14, 2014

How do you implement multiple inheritance in JAVA?

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
    }
}


Thursday, March 29, 2012

What is the ultimate superclass in Java?

What is the ultimate superclass in Java?
The class Object.  All classes in Java that don't explicitly extend another class will implicitly extend this class.

Tuesday, January 17, 2012

What is the difference between Abstract Class and Interface?

What is the difference between Abstract Class and Interface?

Abstract class can have method implementation; interface can't. A class can implement many interfaces, but a class can only extend one Abstract class. Interface fields are constants (static final); Abstract class aren't: their values can be updated.

These are some differences I remember. Please add a comment if you find another one.