Java Interfaces

In this project we look at how to create a Java interface and discuss why creating interfaces is useful.

Interfaces are a key concept in object oriented programming. They serve as a template to insure that all derived classes implement the methods declared in the interface.

Interfaces must never define the method, they only declare it. This is one of the major differences between an interface and an inherited class. The other major difference is that unlike an inherited class a derived class may implement as many interfaces as is needed.

In this simple example we create an interface — Wheel — that declares two methods,  tire and rim. These methods must be defined within the implementing class, Car. We can then create a new instance of a Car and call the methods we’ve created, adding the necessary arguments. 

You may ask yourself why we would want to create an interface, why not just create the Car class and omit the Wheel interface. The reason we create interfaces is to ensure that the derived class implementing the interface creates all the methods necessary for the interface. If we have a truck, a trailer, an SUV all will need wheels and by implementing the wheel they must define the methods. Interfaces are a blueprint of the necessary functionality that must be implemented in the derived class.

				
					interface Wheel {
  public void tire(String brand); 
  public void rim(String brand); 
}


				
			
				
					

class Car implements Wheel {
  public void tire(String brand) {
    System.out.printf("Tire Brand: %s \n", brand);
  }
  public void rim(String brand) {
    System.out.printf("Rim Brand: %s ", brand);
  }
}

				
			
				
					class MyMainClass {
  public static void main(String[] args) {
   Car porche = new Car();
   System.out.println("Car Wheel: ");
   porche.tire("Good Year");
   porche.rim("Titan");
  }
}

				
			

Similar Articles:

Java Projects
Grant

Java Error Control

In this lesson we will be creating a Java project that focuses on handling errors. Error handling is an essential concept in understanding how to make robust systems. By properly handling errors we ensure that the system fails gracefully instead of crashing from an unrecoverable error.

Read More »
Java Projects
Grant

Java User Input

In this lesson we focus on user input by creating a simple application, it is a perfect project for beginners.

Read More »

Leave a Reply

Your email address will not be published. Required fields are marked *