Java Sub-Interfaces.

Java Sub-Interfaces

  • An interface can extend another interface, just as a class can extend another class.
  • Interface is allowed to extend as many interfaces as it wants.
    Sub Interface example:
    interface Pricing {
      public String getPrice();
      public String getDiscount();
      public String DECIMALPATTERN="#";
      public static String getFormatted(double value) {
        DecimalFormat formatter = new DecimalFormat(DECIMALPATTERN);
        return formatter.format(value);
      }
    }
    // Pricing is a sub interface of Reputation
    interface Reputation extends Pricing{
      public String getInfo();
    }
    class Car implements Reputation {
      private final double price, discount;
      private final List<String> reputations= new ArrayList<>();
      public void addReputation(String reputation) {
        reputations.add(reputation);
      }
      public Car(double price, double discount) {
        this.price = price;
        this.discount = discount;
      }
      @Override
      public String getInfo() {
        String returns ="";
        for (String ret : reputations) {
          returns +="\n"+ret;
        }
        return returns;   
      }
      @Override
      public String getPrice() {
        return "$ "+Pricing.getFormatted(price);
      }
      @Override
      public String getDiscount() {
        return Pricing.getFormatted(discount)+"%";
      }
    }
    public class CarReputationApp {
      public static void main(String[] args) {
        Car myCar = new Car(100000,15); // instantiated object of class car
        System.out.println("Ordinary car price is " + myCar.getPrice());
        System.out.println("You've got a car discount of " + myCar.getDiscount());
        myCar.addReputation("\tComfortable to drive");
        myCar.addReputation("\tAdditional winter wheels");
        myCar.addReputation("\t2016 modell");
        System.out.println("Car reputations:" + myCar.getInfo());
      }
    }
    
    The result of this is:
    Ordinary car price is $ 100000
    You've got a car discount of 15%
    Car reputations:
    	Comfortable to drive
    	Additional winter wheels
    	2016 modell
    You can download this example here (needed tools can be found in the right menu on this page).
  • A class that implements Reputation must also implement methods of the sub interface Pricing.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.