Question

I'm a beginner Java programmer and have been experiencing difficulty grasping what the big picture of implementation is in OOP in the Java language.

I will try to frame my question with the pseudocode below (apologies if it is not that pretty):

interface{
  foo();
}

class a {
  //stuff
  foo() OPERATIONS;
}
class b {
  //stuff
  foo() OPERATIONS;
}

//The OPERATIONS segment is actually the *work* the foo does: i.e., if foo were 
//print, it would be the System.out.println("");

Now, what is the purpose of an interface, if it is within the actual classes that the interface's 'foo' OPERATIONS are declared? I thought the purpose of an interface was to create, if you will, a 'method grab bag' that is outside of all of the class obfuscation to keep from having to restructure the hierarchy that could be modified in one portion of code and apply to many implementing classes. In other words, I imagined an interface would be like what a function would be used for in 'C' language: a sequestered and concise set of operations clustered together and encapsulated to be called on when needed, and grouped in a code segment so that one could modify the OPERATIONS of foo within the interface and it apply to ALL classes implementing the interface. What am I missing?

Thanks!

Était-ce utile?

La solution 2

Interface in java is like a contract with the implementing class. When you implement an interface you have to make sure that either you implement all the methods in the interface or make your class abstract. Lets take a real like analogy.

You are creating a Car. Now as you know there can be a number of cars out there i.e. Mercedes, BMW, Audi and so on. You want to make sure that each Car should contain changeGear(), hasWheels(), hasDoors() methods in them, so how would you force this criteria on all possible cars. Simply create an interface named Car that has all these methods in it like

public interface Car{
boolean changeGear();
boolean hasWheels();
boolean hasDoors();
}

Now every class that implements this interface has to implement all these methods. So, in future if you create a Ferrari class implementing Car interface it has to abide by this contract.

Edit: A thing to note here is that all the classes that implement the interface are not restricted to use only the methods from the interface. It is just like the implementing class has to make sure that it at least implements the methods from interface. Like in our example Ferrari class can very well implement the isSportCar() method which is only contained in Ferrari class.

Autres conseils

An interface specifies a contract on what a class does, but not how it does it. Imagine a sort algorithm, there could be many implementations.

public interface Sorter {

    void sort(List<String> list);

}

You could use a bubble sort, a merge sort, quick sort, etc

But as a user of the sorter, I may not care.

class SortClient {

    SortClient(Sorter sorter, List<String> list) {
      sorter.sort(list);
    }

}

The SortClient doesn't care how you sort, just that it gets sorted.

In frameworks that do dependency injection such as Spring or Guice, this becomes very important. These frameworks allow you to configure which implementation is used without changing the user of it.

Interfaces have other practical uses. They are useful for creating mocks/stubs for testing. In the SortClient case above, maybe you want to create some stub for the sorter, such as:

ExceptionThrowingStubSortClient implements Sorter {
   void sort(List<String> list) {
      throw new SortException("Testing the exception handling");
   }
}

Start by having a read through What is an interface?.

Basically an interface is a contract that states that all implementations of the interface guarantee to provide an implementation of the methods described by the interface. It should be noted, that an implementation may decide to implement an empty method instead of providing an actual coded implementation, this is up to the implementation, but it does guarantee that the methods described by the interface can be called on implementations of the interface.

For example...

public interface Foo {
    public void doBar();
}

States that any implementation of foo MUST provide a method called doBar that returns nothing (void)...

An interface can not be instantiated

Meaning you can't do

Foo foo = new Foo(); // Compiler error...

But you can implement the interface in a concrete class...

public class FooBar implements Foo {
    public void doBar() {
        // Functional implementation of doBar...
    }
}

This now allows us to create an instance of FooBar...

FooBar fooBar = new FooBar();
fooBar.doBar();

You can also treat any implementation of Foo as if it was an instance of Foo...

Foo foo = new FooBar();
foo.doBar();

(ps- Yes I know, technically, this isn't an instance of Foo, but simple FooBar acting like Foo ;))

This is at the heart of Polymorphism

This allows you to de-couple your code, as your code doesn't need to care about the implementation of Foo, only that they can interact with Foo.

This also allows you to restrict access to the implementation, meaning that because Foo only defines the method doBar, any method that expects an implementation of Foo won't be able to call any other method then doBar

(ps- Yes I know there are ways around this, but the intention is, you shouldn't!)

This comes to the heart of Program to an interface, no an implementation

An Interface in java is used to set a contract for all classes that are going to implement it and for all those classes those are going to use it for a problem to solve. But not as you said, like it can be used as a reusable function as in c or any other language, because all functions/methods in java are encapsulated inside a class.

An interface is a collection of abstract methods and a class implements an interface, inheriting all the abstract methods declared in the interface. An interface has some similarities to a class, but an interface is not a class. For example, an interface cannot be instantiated, and it cannot contain any instance fields and can have only constants fields such as static final fields.

The purpose of java interfaces is to model a certain behavior that can be common between different objects. Like a man can bounce, and so does a ball so the bounce-able behavior is common between 2 different classes of objects, i.e. a man and a ball

In your pseudocode above the foo interface can describe a certain behavior that is common between classes a & b

Like:

interface Foo{
  void bounce();
}

class A implements Foo {
 public void bounce() {
       System.out.println("Class A instance is bouncing");
 }
}

class B implements Foo {
 public void bounce() {
       System.out.println("Class B instance is bouncing");
 }
}

Rather an interface defines a set of behavior that can be expected from a class. Just the behavior not the implementation. Let me use a trivial example. You have had lessons in driving a car and now that you have a license you can drive a car. Which make of car did you learn to drive? Was it a gas engine or a diesel engine? And most importantly, does it matter?

You learned the interface to a car. Now that you know how to use the interface and what behavior to expect it does not matter how that behavior is implemented. So any make of car, any engine type will be fine with you. Notice also that it was not necessary for you to actually learn how the engine of the car worked in order to drive the car.

In software interfaces are used to specify behavior. Then in your code you can say I need a Foo object that can do the bar() operation. You do not need to know the implementation details of bar(), just what to expect when you call it.

For example, you may decide you need a List collection which may contain duplicate objects. In the Java API there are more than one List implementations, ArrayList and LinkedList for example. You can write code that uses List (the interface) without worrying about which implementation. This in turn makes your code more robust and reusable.

In some ways a Java interface is like a C header file: it declares the the methods/functions that a class has in a separate file.

Why is this useful in an Object Oriented System?

This is useful because other classes can implement the interface, declare those methods and use them in the same way and abide by the rules for those methods (the method contract). Other code can use the call these objects only using the interface and potentially not know or care anything else about the implementation other than it implements the interface.

For example, a java OutputStream (which is technically an abstract class but we can pretend it is an interface in this example) has methods to write bytes

abstract class OutputStream{ 

   void write(int byte);

   void write(byte[] buffer);

   void close();

 }

There are several implementations of OutputStream, some write to flat files, some write to in memory arrays, some write data to the console. If our code uses an OutputStream we don't have to care how to do all those things ourselves AND we can substitute different implementations later either at compile time or at runtime and our code will still work!

Here is a quote from Oracle's doc on interfaces:

interface Bicycle {

//  wheel revolutions per minute
void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement); 

}

To implement this interface, the name of your class would change (to a particular brand of bicycle, for example, such as ACMEBicycle), and you'd use the implements keyword in the class declaration:

class ACMEBicycle implements Bicycle {

// remainder of this class 
// implemented as before 

}

And here is the link to find out more.

Hope it helped!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top