Signup/Sign In
APRIL 19, 2023

Java Interface and abstract classes

Technology #class#java

    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.

    I have been into tech development for around 9 years now have a good hands on with the languages ike java,python php etc. I have a pretty good interest in Design and Algorithms as well.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS