Advertisement

header ads

Java OOP Interfaces - A simple tutorial


Interface is a collection of abstract method. It also define as a reference type in java. This java interfaces tutorial provides a simple example to understand interfaces easily.

  • special keywords: interface
  • Apart from abstract methods, an interface can contain default methods, static methods and constants.
  • All above methods should be implement in inherited class.
  • Abstract methods in interfaces do not use 'abstract' keyword all methods defined in an interface are abstract by default.

Try following example to get a clear idea about interfaces in java.

This is Car.java interface
It contains 2 abstract methods
1
2
3
4
5
6
7
8
public interface Car {

 public void buildChassis(String color);

 public void buildEngine(double engineCapacity);
 
 
}

This is Lamborghini.java class
This class implements the all abstract methods of Car.java class
Then Lamborghini class has been instantiated in main class.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
public class Lamborghini implements Car {

 @Override
 public void buildChassis(String color) {
  System.out.println("Chassis was built with color: " + color);

 }

 @Override
 public void buildEngine(double engineCapacity) {
  System.out.println("Engine was built with capacity: " + engineCapacity);

 }

 public static void main(String[] args) {
  Lamborghini lamborghini = new Lamborghini();
  lamborghini.buildChassis("black");
  lamborghini.buildEngine(30000);
 }
}

Output:
Chassis was built with color: black
Engine was built with capacity: 30000.0

Apart from above functionalities, interfaces  support multiple extending (line 13).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public interface Car {

 public void buildChassis(String color);

 public void buildEngine(double engineCapacity);

}

interface Lamborghini extends Car {

}

interface LamborghiniEngine extends Lamborghini, Car {

}

These are the basic functionalities of interfaces. You can try above simple examples on your own and proceed with some complex codes. Share this tutorial among friends. Like our facebook page to stay upto date with latest tutorials.

Post a Comment

1 Comments

  1. I was pleased with the game in this casino I will continue to play constructive internet blackjack therefore, I advise you and you will not regret

    ReplyDelete