Grumpy ol' Bear
Grumpy ol' Bear

Reputation: 745

How does an Interface in Java work?

I'm self learning Java, and I'm stuck on a chapter about Interfaces. I simply cannot understand how they work in Java.

I believe I understand perfectly what Interface means and how they apply in everyday situations and technology.

But when it comes to Java, code-wise and logic-wise, I'm stuck. I don't get it. How does the concept work?

Say I have 3 objects, and 1 interface object. 2 Objects are ObjectCalculatingA, ObjectCalculatingB, ObjectMathFunctions, and ObjectInterface.

Supposedly in ObjectInterface there must be some sort of reference to the ObjectMathFunctions, so that ObjectCalculatingA and B can just access the math functions in ObjectMathFunctions without writting them all again in A and B.

Am I right?

Upvotes: 3

Views: 10074

Answers (4)

dodgy_coder
dodgy_coder

Reputation: 13063

If you know that a class can consist of both data and the functions that operate on the data, then an interface is just a list of the functions that a class has to implement.

Take a light switch interface, ILightSwitch ...

public interface ILightSwitch {
    void turnOn();
    void turnOff();
}

A class implements an interface if it implements those functions above.

e.g. A LightSwitch class might be

public class LightSwitch implements ILightSwitch {
    boolean on = false;
    void turnOn() { on = true; }
    void turnOff() { on = false; }
}

The LightSwitch class implements the ILightSwitch interface.

Upvotes: 2

Jasper Blues
Jasper Blues

Reputation: 28786

An interface exists to facilitate polymorphism. It allows declaring a contract that any class that implements the interface must honor. And so it is a way to achieve abstraction and model complexity by looking for commonality between things.

An example? How about shapes? All shapes have an area, right? So you could have the following classes:

  • Square
  • Circle

Then let's say you have another class that allows you to collect shapes, and return the total area:

for (Shape shape in shapes)
{
    area += shape.area()  //This is polymorphism
}

In the example above, we don't care whether the shape is a square or a circle. We can accept either. We only care that it implements the Shape interface. Each object will provide their own custom implementation of area - these internal details aren't important, only that it honors the area contract . See now how we're managing complexity? We can use the class without having to worry about all of the things that go on inside. At this point what it does is important to us, not how it does it, which lets us focus on the problem at hand not getting distracted by complex details.

This polymorphism is one of the reasons why object oriented programming was considered such a powerful evolutionary step in programming. The other key foundation concepts in Object Oriented Programming are:

. . . you'll also need to learn these.

Abstract Base Class vs Interface

As a comment said, another way to achieve polymorphism is to use an Abstract Base Class. Which should you choose?

  • Use an interface class implementing it will have its own hierarchy and dependencies. For example a media player. A Movie Player and a Sound Player might have totally different base classes, so use an interface.

  • Use an Abstract base class when you have some commonality between things, but the specifics vary. For example a message parsing framework.

Upvotes: 4

parasietje
parasietje

Reputation: 1539

From your example, it shows that you lack a basic understanding of Object-Oriented Programming. You are trying to learn how to run without having learned to stand up yet.

In your example, you assume there is a class ObjectMathFunctions. This is not Object-oriented at all, classes should model a real concept.

1. Learn about objects / classes

You should first learn how classes and objects work. A class is not just any arbitrary division of code, it models something real. Examples: Car, Wheel, etc.

2. Learn about inheritance

After you understand that, learn about inheritance: a Car has a getWeight() method. A Wheel has a getWeight() method as well. Hmm, maybe they are both subdivisions of a broader concept: PhysicalThings. Every PhysicalThing has a getWeight() method.

After this, learn about overriding methods in subclasses, learn about abstract classes, etc.

3. Learn about interfaces

Now you will understand that an interface is very similar to an abstract class. You will have done some exercises where you already encountered the problem "This is a PhysicalThing, but it is also CanExplode (e.g. wheel of car, dynamite, etc). This single inheritance model is annoying, how do I fix this?".

Upvotes: 2

Pratik Shelar
Pratik Shelar

Reputation: 3212

In simple lay mans language. Interface is a contract and classes implementing the interface need to adhere to the contract. There can be many implementations for same interface and users can select which implementation they wish to use. For more detailed information I suggest you read book like HeadFirst JAVA.

Once you begin software development you will understand that many a times you would come across an already implemented piece of code which you feel is not properly implemented. But at the same time a colleague of yours feels its correctly implemented and serves his purpose. This is where interfaces come into play. Your colleague who feels this implementation works for him can continue using the current one whereas you can implement your new implementation but you need to make sure that it adheres to the interface so that in future if your implementation is better, your colleague will have an oion to switch over.

List<String> myList = new ArrayList<String>();

In above example arraylist is on of the implementations of the List interface. Consider this example, ArrayList is not suiting your requirments so you can do the following.

myList = new LinkedList<String>();

This is the power of 'Coding to interface'

Upvotes: 4

Related Questions