Technology3 min read

Java Interface and abstract classes

Abhishek Ahlawat

By Abhishek Ahlawat โ€” APRIL 19, 2023

Founder of StudyTonight and a MERN fullstack developer. Writes about JavaScript, web development, Linux, and tech.

#class#java

Summarize this article using AI

Interface in Java

The interface is similar to the class, except it contains only abstract methods. It does not contain methods body.

The interface must be implemented by a class to provide the body (definition) of its methods.

It cannot be instantiated, so its methods can only be accessed by using the class object.

An interface may have variables that are final by default.

To create an interface, use the interface keyword as you did with creating class in the previous lesson.

Syntax

interface <interface-name>{
	// variables
	// methods
}

For example,

interface Car{
	int speed = 0;
	void showSpeed(int speed);
}

Sample Code

interface Car{
	void showSpeed(int speed);
}
class BMWCar implements Car{
	@Override
	public void showSpeed(int speed) {
		System.out.println("Car Speed: "+speed);
	}
}
class FordCar implements Car{
	@Override
	public void showSpeed(int speed) {
		System.out.println("Car Speed: "+speed);
	}
}
public class MainClass{	
	public static void main(String[] args) {	
		BMWCar car = new BMWCar();
		car.showSpeed(120);
		FordCar fcar = new FordCar();
		fcar.showSpeed(100);
	}
}

Create Interface

To create an interface, use interface keyword and any valid name. We can add any number of methods and variables to the interface. To use this interface, it must be implemented by a class.

Let's learn to create an interface.

Create a Bike interface by using the interface keyword. Initially, it is empty, which means it does not contain any method or variable. Hint

interface Bike{

}

After creating the interface, run the code.

This is how, we created interface. Initially it does nothing. It is just declaration.

interface Car{
	void showSpeed(int speed);
}

In the next lesson, we will learn to implement this interface in the class.

Spotted something outdated or wrong?

Liked this? See more StudyTonight posts in Google results.

Add StudyTonight as a preferred source
Next questLIVE OPSStep 2 / 3

Practice real incidents in the browser

System Design Ops โ€” put out fires, ship fixes, and stack XP. Reading done. Time to play.

Play System Design
  • +XP

    Every sim

  • Incidents

    Live ops

  • Ranks

    Climb up

Read next