Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

Let us say you have an interface:

public interface Change {

    void updateUser();

    void deleteUser();

    void helpUser();

}

I have read that the interface is Java’s way to implement multiple inheritances. You implement an interface, then you have access to its methods. What I don’t understand is, the methods don’t have any body in the interface, so you need to give the method a body in more than one class. Why is this better than just having individual methods in your classes, and not implementing an interface?

1 Answer

0 votes
by (13.1k points)

Why is this better than just having individual methods in your classes, and not implementing an interface?

Because if a class C implements an interface I, you can use a C whenever an I  is expected. If you don’t implement the interface, you could not do this:

interface I {

    void foo();

}

class C1 implements I {

    public void foo() {

        System.out.println("C1");

    }

}

class C2 {  // C2 has a 'foo' method, but does not implement I

    public void foo() {

        System.out.println("C2");

    }

}

...

class Test {

    public static void main(String[] args) {

        I eye1 = new C1();  // works

        I eye2 = new C2();  // error!

    }

}

Want to learn Java? Check out the Java certification from Intellipaat.

Browse Categories

...