Java – Static and Default Methods

Interface (since jdk7):

  • Interface allowed to define static methods from jdk7
  • Static methods can access using identity of interface.

Note: Static methods are used to define the common functionality of objects which are implemented from that interface.

interface CreditCard
{
            String cartType = “VISA-Platinum”;
            static void benefits(){
                        System.out.println(“Benefits on Flying, Dining and more”);
            }
}

Default Methods:

  • Defining a method with default keyword.
  • We can access Default methods through object reference.

Note: Default methods allow the interfaces to have methods with implementation without affecting the classes that implement the interface.

interface Vehicle
{
            default String airBags(){
                        return “Two airbags”;
            }
            default String alarmOn(){
                        return “at speed of 100”;
            }
            int maxSpeed();
}
class Alto implements Vehicle
{
            public int maxSpeed(){
                        return 160;
            }
}
class Swift implements Vehicle
{
            public int maxSpeed(){
                        return 220;
            }
}
Scroll to Top