Ashish
Ashish

Reputation: 309

Difference between interface-abstract (not duplicate)

I want to know the difference between the two codes. I have a interface: lets say :

public interface iaminterface {
      void m1();
      void m2();
      void m3();
}

First Code :

public abstract class iamabstract implements iaminterface  {
     public void m1(){}
     public abstract void m2();  // abstract method .So i need to override this in the subclasses. 
}

public class car extends iamabstract {
public void m2(){}
public void m3(){}
}


public class train extends iamabstract {
public void m2() {}
public void m3() {}
}

This code will compile successfully. But this code is same as writing :

Second Code:

 public abstract class iamabstract implements iaminterface {

     public void m1(){}

}

public class car extends iamabstract {
public void m2(){}
public void m3(){}
}


public class train extends iamabstract {
public void m2() {}
public void m3() {}
}

I don't understand the difference in the two codes. Both codes will function in a similar way. One has a abstract method and another does not have a abstract method, so we need to implement the unimplemented methods of the interface. So , what's the use of writing the method m2() as abstract in the first code. ?

Upvotes: 1

Views: 60

Answers (1)

Craig Otis
Craig Otis

Reputation: 32054

The only reason you would want to override the interface method in your abstract class is if you wanted to be more specific about the type returned. For example:

public interface TheInterface {
    Object getTheObject();
}

public abstract class TheAbstractClass implements TheInterface {
    @Override
    public abstract String getTheObject();
}

Note that even though the @Override annotation is used, the abstract class method actually returns a String instead of an Object. This does not break the contract that an object implementing TheInterface will return an Object from that method - a String is an Object, after all.

However, it does allow you to work with a concrete subtype of TheAbstractClass and know for certain that it will give you a String.

Upvotes: 2

Related Questions