Similar to classes, but they does not contain any method implementations. An interface can extend other interfaces. Vehicle is a general interface, Car extends from a Vehicle it has more specific functions, similar to Motorcycle.
Vehicle.java
public interface Vehicle
{
public void hasWheels();
public void hasEngine();
}
Car.java
public interface Car extends Vehicle
{
public void hasDoors();
public void hasAirbags();
public void hasRoof();
}
Motorcycle.java
public interface Motorcycle extends Vehicle
{
public void hasPedal();
public void hasHandlebars();
public void hasStand();
}
Exercise 1.
public class TryItOut {
public static void main(String[] args) {
// creating a car array with 10 elements
Car car[] = new Car[10];
// create Skodas and BMWs (depending on the i-th index)
for(int i=0; i < 10; i++) {
if(i%2 == 0) {
car[i] = new Skoda();
} else {
car[i] = new BMW();
}
}
// call hasAirbags() method on each instance
for(int i=0; i < 10; i++) {
car[i].hasAirbags();
}
}
}