Md Sagar Mia Md Sagar Mia - 14 days ago 7
Java Question

Why Class can not extends Interface in java?

interface a{
public void getSum();

}
public class b implements a{

public void getDivision(){

}
}


We know that but
why class b can not extends interface a ?
What's the reason?

Answer

Why can class B not extend the interface A? What's the reason?

The reason is that inheriting from classes (extending them), and implementing interfaces are two different concepts.

Because they are two different concepts, they have different keywords (implements and extends).

Extending a class (Inheritance)

When you extend a class, you inherit all of its fields and methods.

For example:

public class A {
    void runInheritedMethod() {
        System.out.println("Hello");    
    }
}

public class B extends A {
}

public class Main {
    public static void main(String[] args) {
        // This is valid code...
        B bInstance = new B();
        bInstance.runInheritedMethod();
    }
}

Implementing an interface

When you Implement an interface, your class will contain "bodies" or "implementations" for all of the unimplemented functions of said interface.

For example:

public interface Choppable {
    public void chop();
}

public class Wood implements Choppable {
    public void chop() {
        // Your wood-specific code here...
    }
}

public class Carrot implements Choppable {
    public void chop() {
        // Your carrot-specific code here...
    }
}

Both of these concepts can be used to achieve polymorphic behaviour, which is why they can cause confusion.