Topics Index
In Java, there comes a situation where we need to add an extra method to an already existing interface which will effect the functionality of all the classes implementing that particular interface. In order to avoid such situations Java have a special feature called extending interface using this concept a newly declared interface can extend the methods of an already existing interface.

The keyword extends is used to extend the interface.

The following program explains clearly the extending interface concept.
class ExtendsInterfaceDemo
    public static void main(String arg[])
        vehicle v1 = new Bike();   // LINE A
        OtherFeatures v2 = new Car();
        v2.companyName("Hyundai"); // LINE B

interface vehicle  // LINE C

    void companyName(String name);

    void vehicleName(String name);

    void vehicleType(int i);

    void seatArrangement(int i);

interface OtherFeatures extends vehicle // LINE D

    void mileagePerLiter(int i);
class Bike implements vehicle // LINE E

    public void companyName(String name)
        System.out.println(name + "'s product.");

    public void vehicleName(String name)
        System.out.println("Name of vehicle : " + name);

    public void vehicleType(int i)
        System.out.println(i + " wheeler.");

    public void seatArrangement(int i)
        System.out.println(i + " seater capacity.");

class Car extends Bike implements OtherFeatures // LINE F

    public void mileagePerLiter(int i)
        System.out.println("Mileage : " + i + " Kmpl.");

Honda's product.
Name of vehicle : Shine
2 wheeler.
2 seater capacity.
Hyundai's product.
Name of vehicle : i10
4 wheeler.
5 seater capacity.
Mileage : 20 Kmpl.


In the above program at LINE C, we have created an interface vehicle with abstract methods companyName, vehicleName, vehicleType, seatArrangement and we also created one more interface otherFeatures at LINE D, with mileagePerLiter method which extends vehicle. we have create two classes Bike and Carat LINE E and LINE F, Bike implements vehicle it provides body for vehicle methods and Car implements otherFeatures and provides body for only mileagePerLiter, since Car extends Bike methods in Bike are accessible by Car also. At LINE A we have created an object for Bike with vehicle reference and accessed the methods of Bike class. At LINE B we have created another object for Car with otherFeatures reference

  • At LINE E in class Bike remove the method companyName it shows a compilation error as java.lang.Error: Unresolved compilation problem: The type Bike must implement the inherited abstract method vehicle.companyName(String)
  • Try for the following code :
    The code throws compilation error, since the subclass methods are not accessible by super class.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App