10

Possible Duplicate:
What does it mean to “program to an interface”?
Interface vs Abstract Class (general OO)

I'm new to learn JAVA and now I'm confused about interface. I have searched and read many materials but still not clear.

When I try to find some information about interface, I see many people talked about the relationship between interface and abstract class. But I even don't know why they contrast these two. Because I think abstract class is used to tell other people you can not create an object of this abstract class and if you want, you must modify the abstract class. This is something about inheritance, right?

But I don't know the meaning of interface. There is a interface a, and if a class B is going to implement the interface a, it must use the reserved word class B implements a, and then complete all the methods that the interface requires. But my question is, if class B have to complete all the methods by itself, what's the meaning of interface? I think we don't need it. I don't understand it very much. I read many sentences like: "interface can reflect the core thought of object-oriented language", "interface can help make the program easier" and so on. But I can not really understand the meaning.

So, does anyone can show me some examples to let understand interface? Or you can tell me some useful links or the books that describe the interface clearly. I really hope to figure it out. THANK YOU!

Community
  • 1
  • 1
lkkeepmoving
  • 2,323
  • 5
  • 25
  • 31
  • it may help to explore you more about interfaces in java: http://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface – Jimmy Oct 20 '12 at 22:10
  • The sole purpose of an interface is to achieve *the publicly defined protocol behaviour* meaning that the class that inherits interface(s) must incorporate all the methods defined by that interface is a rule or more specifically it's *a protocol definition* for that class. (every thing you define within an interface must be public anyway). – Lion Oct 20 '12 at 22:12

5 Answers5

10

Suppose you have a Car class and Vegetable class which is unrelated in real life and there is a common behaviour called wash(). Because we can wash a car and wash a vegetable too. But washing a car and washing a vegetable is totally different process/behaviour.

For ex: Car should be washed with a power pump, Vegetables under your kitchen sink. So the way of washing is different. So you make the washing process as a method wash() in the interface say Washable and you implement them in both Car and Vegetable class.

interface Washable {

 public void wash();

} 

public class Car implements Washable {

 public void wash() {

   // wash the car with a power pump

 }


}

public class Vegetable implements Washable {

public void wash() {

   // wash the vegetable under a kitchen sink

 }


}

As a person, you would want to wash a car as well as vegetable.

public class Person  {


Washable washableObject = new Car();

washableObject.wash();

washableObject = new Vegetable();

washableObject.wash();




}
  1. So interface is a way to connect unrelated classes which has a common behavior.But the behavior will be differently implemented or can be changed in future.

  2. One day you decide to change the way you wash a Car.Suppose you have purchased a "car washing machine". So the implementation changes inside the method wash() in the Car class.

    public class Car implements Washable {

      public void wash() {
    
       // wash the car with my new car washing machine !!
    
     }
    

    }

But as a Person , you still call the wash() method. The way the wash() method is being implemented changed ( washing the car with your new car washing machine ), this implementation change did not affect your Person class.

Hope you are clear why we use interfaces now.

Tito
  • 8,894
  • 12
  • 52
  • 86
  • Great! It's vivid and clear! Thank you! – lkkeepmoving Oct 21 '12 at 20:30
  • 1
    Yes, very clear and easy to understand. But why? I don't see any benefit. You know you're washing a car because you instantiated it as a new Car(). You could just have a parent class called Washable, make wash() abstract, and have both Car and Vegetables inherit from Washable, implementing their version of wash(). What am I missing? – SMBiggs May 10 '16 at 05:55
  • 2
    @ScottBiggs Imagine you have a class SuperWashMachine with a method washAll(). It receives an array of Washable. You just need to go through the array and call the wash() method because the "contract" says any class implementing Washable knows how to do it. That's it, this method doesn't even need to know about any Car, Vegetable or whatever specific class, it just deals with Washable things. Why not using inheritance? Well, maybe it's something semantic. Ideally a Car and a Vegetable should have more in common besides being Washable to set an "is a" relationship with a common father class. – Mauricio Martinez Oct 06 '17 at 17:12
  • the same task we can also process with abstract class, So why you have not used the abstract class here instead of an interface? – nirazverma Jan 02 '21 at 12:29
1

Basically, interface is a way to accomplish multiple inheritance without actually having to do it. (Which is not to say that the Java folks "wimped out" -- multiple inheritance is exceedingly messy and inefficient to implement.)

What this means is that you can have two totally separate classes A and B, with no common ancestor other than Object, and, if they implement the same interface, you can substitute one for the other (so long as you reference only methods in the interface).

Hot Licks
  • 47,103
  • 17
  • 93
  • 151
1

Think in interfaces like contracts between a class and the user. When a class implements an interface is telling that it promise to offer all the methods defined by the interface.

David Moreno García
  • 4,423
  • 8
  • 49
  • 82
1

Assuming you understand class inheritance, I think of an Interface like a skeleton class, where the structure of a class is described but not actually written/implemented.

Another class can then work with any class that implements a particular Interface even if it hasn't been implemented yet.

For example, someone may create an Interface called Animal. Its methods maybe: Talk(), Walk() and Eat(). You could write a Dog class that implements Animal that prints "woof" when the Talk() method is called. Therefore another class will know how to work with all classes that implements the Animal interface.

UPD

A good real world example is the JDBC Database Statement Interface. This sets out a number of required properties that a database manufacturer will have to implement, such as execute(String sql). Oracle will implement this differently from Postgresql. This allow the database to be swapped for another one but the user code remains the same.

Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100
1

A simple code to understand the interface and class.

import java.util.List;
import java.util.ArrayList;
public class Q01 {
List<Shape> shapes= new ArrayList();

public void add() {
    shapes.add(new Square(3.0));
    shapes.add(new Circle(2.0));
}
public void print() {
    for (int i = 0; i < shapes.size(); i++) {
        Shape shape = shapes.get(i);
        System.out.println(shape.getClass().getSimpleName() + " --->" + shape.getArea());
    }
}

public static void main(String[] args) {
    Q01 q01= new Q01();
    q01.add();
    q01.print();
}

public interface Shape {
    double getArea();
}

public class Square implements Shape{
    private double edge;

    public Square(double edge) {
        this.edge = edge;
    }
    public double getArea() {
        return edge*edge;
    }
}
public class Circle implements Shape{
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getArea() {
        return 3.14 * radius * radius;
    }
}
}
chrome
  • 661
  • 2
  • 7
  • 23