Thursday, 15 June 2023

Static Methods in interfaces

 The static methods in interfaces are similar to default methods but the only difference is that you can’t override them. Now, why do we need static methods in interfaces if we already have default methods?

Suppose you want to provide some implementation in your interface and you don’t want this implementation to be overridden in the implementing class, then you can declare the method as static.

Since static methods don't belong to a particular object, they're not part of the API of the classes implementing the interface; therefore, they have to be called by using the interface name preceding the method name.

 Let us consider the following program 

public interface Vehicle {



    static void cleanVehicle(){

        System.out.println("I am cleaning vehicle");

    }

}

public class Car1 implements Vehicle {

    

    public static void main(String args[]){

        Car1 car = new Car1();

        Vehicle.cleanVehicle();  //This will not compile.

        

    }

}

The following is the output of the program

0 comments :

Post a Comment

Note: only a member of this blog may post a comment.

Machine Learning

More

Advertisement

Java Tutorial

More

UGC NET CS TUTORIAL

MFCS
COA
PL-CG
DBMS
OPERATING SYSTEM
SOFTWARE ENG
DSA
TOC-CD
ARTIFICIAL INT

C Programming

More

Python Tutorial

More

Data Structures

More

computer Organization

More
Top