0% found this document useful (0 votes)
3 views36 pages

Default Methods

Java 8 introduced default methods in interfaces, allowing them to have method implementations without breaking existing classes. This feature enhances backward compatibility, enables the addition of new methods, and helps avoid utility classes. Default methods can be overridden in implementing classes, and they differ from static methods, which belong solely to the interface.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views36 pages

Default Methods

Java 8 introduced default methods in interfaces, allowing them to have method implementations without breaking existing classes. This feature enhances backward compatibility, enables the addition of new methods, and helps avoid utility classes. Default methods can be overridden in implementing classes, and they differ from static methods, which belong solely to the interface.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

==========Default Methods =================

Java Default Methods

Default methods |Defender method |Virtual Extension method

Before Java 8 (up to Java 7):

Interfaces could contain only abstract methods and constants.

All interface methods are implicitly public abstract, even if not declared.

All interface variables are implicitly public static final, even if not declared.

From Java 8 onwards:

Interfaces can also contain default methods.

A default method is a non-abstract method declared using the default keyword and includes a
method body.
Default methods allow interfaces to provide implementations without breaking existing classes
that implement the interface.

Syntax: We can declare default method with the keyword “default” as follows

default void m1(){

[Link] (“Default Method”);

Need:

Default methods in Java 8 also known as defender methods allow Java developers to add new
methods to the existing interfaces in their code without breaking their current implementation

Before Java 8, interfaces could have only abstract methods. The implementation of these
methods has to be provided in a separate class. So, if a new method is to be added in an
interface, then its implementation code has to be provided in the class implementing the same
interface. To overcome this issue, Java 8 has introduced the concept of default methods which
allow the interfaces to have methods with implementation without affecting the classes that
implement the interface.

Important Points:

Interfaces can have default methods with implementation in Java 8 on later.

Interfaces can have static methods as well, similar to static methods in classes.

Default methods were introduced to provide backward compatibility for old interfaces so that
they can have new methods without affecting existing code.

Important points about java interface default methods:

Java interface default methods will help us in extending interfaces without having the fear of
breaking implementation classes.

Java interface default methods has bridge down the differences between interfaces and abstract
classes.

Java 8 interface default methods will help us in avoiding utility classes, such as all the
Collections class method can be provided in the interfaces itself.
Java interface default methods will help us in removing base implementation classes, we can
provide default implementation and the implementation classes can chose which one to
override.

One of the major reason for introducing default methods in interfaces is to enhance the
Collections API in Java 8 to support lambda expressions.

If any class in the hierarchy has a method with same signature, then default methods become
irrelevant. A default method cannot override a method from [Link]. The reasoning is
very simple, it’s because Object is the base class for all the java classes. So even if we have
Object class methods defined as default methods in interfaces, it will be useless because Object
class method will always be used. That’s why to avoid confusion, we can’t have default methods
that are overriding Object class methods.

Note:

We can’t override object class methods as default methods inside interface otherwise we get
compiletime error.

Ex:

interface Interf {
default inthashCode() {

return 10;

CompileTimeError

Reason: object class methods are by-default available to every java class hence it’s not required
to bring through default methods.

Java interface default methods are also referred to as Defender Methods or Virtual extension
methods.

Default method you can declare in interface only not in class in class it define it as public not
Default , otherwise it gives error modifer default is not allowed. beacause within class for
default there is another meaning ie switch statement
interface Interf{

default void m1()

System. out print1n("Default Method");

class Test implements Interf

public void m1(){

[Link]("overriding version of default method");

public static void main (String[] args)

{
Test t = new Test();

t.m1();

Java Default Method Example

In the following example, Sayable is a functional interface that contains a default and an
abstract method. The concept of default method is used to define a method with default
implementation. You can override default method also to provide more specific implementation
for the method.

Let's see a simple

interface Sayable{
// Default method

default void say(){

[Link]("Hello, this is default method");

// Abstract method

void sayMore(String msg);

public class DefaultMethods implements Sayable{

public void sayMore(String msg){ // implementing abstract method

[Link](msg);

public static void main(String[] args) {

DefaultMethods dm = new DefaultMethods();


[Link](); // calling default method

[Link]("Work is worship"); // calling abstract method

Output:

Hello, this is default method

Work is worship

Static Methods inside Java 8 Interface

You can also define static methods inside the interface. Static methods are used to define utility
methods. The following example explain, how to implement static method in interface?

interface Sayable{

// default method
default void say(){

[Link]("Hello, this is default method");

// Abstract method

void sayMore(String msg);

// static method

static void sayLouder(String msg){

[Link](msg);

public class DefaultMethods implements Sayable{

public void sayMore(String msg){ // implementing abstract method

[Link](msg);
}

public static void main(String[] args) {

DefaultMethods dm = new DefaultMethods();

[Link](); // calling default method

[Link]("Work is worship"); // calling abstract method

[Link]("Helloooo..."); // calling static method

Output:

Hello there

Work is worship

Helloooo...
Abstract Class vs Java 8 Interface

After having default and static methods inside the interface, we think about the need of
abstract class in Java. An interface and an abstract class is almost similar except that you can
create constructor in the abstract class whereas you can't do this in interface.

abstract class AbstractClass{

public AbstractClass() { // constructor

[Link]("You can create constructor in abstract class");

abstract int add(int a, int b); // abstract method

int sub(int a, int b){ // non-abstract method

return a-b;

static int multiply(int a, int b){ // static method

return a*b;

}
}

public class AbstractTest extends AbstractClass{

public int add(int a, int b){ // implementing abstract method

return a+b;

public static void main(String[] args) {

AbstractTest a = new AbstractTest();

int result1 = [Link](20, 10); // calling abstract method

int result2 = [Link](20, 10); // calling non-abstract method

int result3 = [Link](20, 10); // calling static method

[Link]("Addition: "+result1);

[Link]("Substraction: "+result2);

[Link]("Multiplication: "+result3);
}

Output:

You can create constructor in abstract class

Addition: 30

Substraction: 10

Multiplication: 200

Default Methods and Multiple Inheritance

Two interfaces can contain default method with same signature then there may be a chance of
ambiguity problem(diamond problem) to the implementation [Link] overcome this problem
compulsory we should override default method in the implementation class otherwise we get
compiletime [Link] class should explicitly specify which default method is to be
used

Example 1:

// A simple Java program to demonstrate multiple


// inheritance through default methods.

interface TestInterface1

// default method

default void show()

[Link]("Default TestInterface1");

interface TestInterface2

// Default method
default void show()

[Link]("Default TestInterface2");

// Implementation class code

class TestClass implements TestInterface1, TestInterface2

// Overriding default show method

public void show()

// use super keyword to call the show


// method of TestInterface1 interface

[Link]();

// use super keyword to call the show

// method of TestInterface2 interface

[Link]();

public static void main(String args[])

TestClass d = new TestClass();

[Link]();

}
}

Output:

Default TestInterface1

Default TestInterface2

Example 2:

interface Left {

default void m1() {

[Link]("Left Default Method");

}
}

interface Right {

default void m1() {

[Link]("Right Default Method");

class Test implements Left, Right {}

How to override default method in the implementation class?

In the implementation class we can provide complete new implementation or we can call any

interface method as follows.


[Link].m1();

class Test implements Left, Right {

public void m1() {

[Link]("Test Class Method"); OR [Link].m1();

public static void main(String[] args) {

Test t = new Test();

t.m1();

Example 3:

interface MyInterface
{

default void newMethod() {

[Link]("Newly added default method");

interface MyInterface2

default void newMethod() {

[Link]("Newly added default method");

}
public class Example implements MyInterface, MyInterface2

public static void main(String[] args) {

Example obj = new Example();

// calling the default method of interface

[Link]();

Output:

Error: Duplicate default methods named newMethod with the parameters () and () are inherited
from the types MyInterface2 and MyInterface

This is because we have the same method in both the interface and the compiler is not sure
which method to be invoked.
How to solve this issue?

To solve this problem, we can implement this method in the implementation class like this:

interface MyInterface{

default void newMethod(){

[Link]("Newly added default method");

interface MyInterface2{

default void newMethod(){

[Link]("Newly added default method");


}

public class Example implements MyInterface, MyInterface2{

//Implementation of duplicate default method

public void newMethod(){

[Link]("Implementation of default method");

public static void main(String[] args) {

Example obj = new Example();

//calling the default method of interface

[Link]();

}
}

Output:

Implementation of default method

Differences between interface with default methods and abstract class

Eventhough we can add concrete methods in the form of default methods to the interface , it
wont be equal to abstract class.

Interface with default method != abstract class

Interface with Default Methods

Abstract Class

Inside interface every variable is Always public static final and there is No chance of instance
variables
Inside abstract class there may be a Chance of instance variables which Are required to the child
class. Interface never talks about state of Object. Abstract cl

Interface never talks about state of Object.

Abstract class can talk about state of Object.

Inside interface we can’t declare Constructors.

Inside abstract class we can declare Constructors.

Inside interface we can’t declare Instance and static blocks

Inside abstract class we can declare Instance and static blocks.

Functional interface with default Methods Can refer lambda expression.

Abstract class can’t refer lambda Expressions.

Inside interface we can’t override Object class methods.

Inside abstract class we can override Object class methods.


Comparison Table

Feature

Interface (with Default Methods)

Abstract Class

Purpose

Defines a contract (what to do) with optional default behavior

Provides a common base with shared state and behavior

Method Types

Abstract, default, static, and private (Java 9+)

Abstract, concrete, final, static, private, etc.

Constructors

❌ Not allowed

✅ Allowed
Instance Variables

❌ Not allowed (only public static final constants)

✅ Allowed

State (Data)

Cannot maintain object state

Can maintain object state

Access Modifiers

Abstract methods are public by default

Methods can have any access modifier

Inheritance

A class can implement multiple interfaces

A class can extend only one abstract class

Keyword
implements

extends

Object Creation

Cannot create objects

Cannot create objects directly

Method Implementation

Optional implementation through default methods

Full implementation allowed

Use Case

Common capability across unrelated classes

Common base class with shared code and state

Can We Override Default Method in Java?


[Link]

==================== Interview Question ================

Why are there default methods in Java 8?

The default methods were primarily introduced to resolve compatibility issues in Java. Before
default methods in Java 8, interfaces could only have abstract methods. Developers had to
provide the implementation of these methods in a separate class

Why do we need to implement a default method within the interface?

Consider a scenario where you have an interface that has multiple methods, and various classes
are implementing this interface. Introducing a default method simplifies it because the
implementation would be common for all classes.

In another scenario where you need to fulfill a new requirement, you will have to add a new
method to an existing interface. Adding a new method will require implementing it throughout
the implementation classes. By using the Java 8 default method you can easily add a default
method that will not require to add its implementation in any other classes.

Can we override default methods in Java?

Yes,we can

interface MyInterface

public static int num = 100;

public default void display() {

[Link]("display method of MyInterface");

}
public class InterfaceExample implements MyInterface

public void display() {

[Link]("display method of class");

public static void main(String args[])

InterfaceExample obj = new InterfaceExample();

[Link]();
}

Output:

display method of class

EX 2: We can’t override object class methods as default methods inside interface otherwise we
get compiletime error.

Ex:

1) interface Interf {

2) default inthashCode() {

3) return 10;

4) }
5) }

CompileTimeError

Reason: object class methods are by-default available to every java class hence it’s not required
to bring through default methods.

Difference between default and static interface method in Java 8.

No

Key

Static Interface Method

Default Method
1

Basic

It is a static method which belongs to the interface only. We can write implementation of this
method in interface itself

It is a method with default keyword and class can override this method

Method Invocation

Static method can invoke only on interface class not on class.

It can be invoked on interface as well as class

Method Name

Interface and implementing class , both can have static method with the same name without
overriding each other.

We can override the default method in implementing class


4.

Use Case

It can be used as a utility method

It can be used to provide common functionality in all implementing classes

You might also like