r/javahelp • • Nov 09 '18

what is the benefit of creating interface in java

what is the benefit of creating interface in java

27 Upvotes

32 comments sorted by

5

u/TurnupTadpole Nov 09 '18

It allows you to make a bunch of similar classes/objects with the same methods and names, while still allowing you to override the methods so that they each perform appropriately

Ex. After creating a List interface you could have linked list and arraylist classes with addtofront(), addtoback(), removefromfront(), removefromback(), size(), etc. This let's you have consistent method naming throughout methods with similar functions making the whole process easier.

4

u/tehleel_mir_official Nov 09 '18

i don't understand,,

8

u/TurnupTadpole Nov 09 '18

Right so imagine you're building a fps game with a bunch a bunch of guns.

You can have 15 guns and each one will have methods for shoot(), aimdownsights(), and reload().

Shoot will be pretty much the same for all of them, but aimdownsights (), and reload() will be different as the will have different capacities, reload time, aim time etc.

If you just made one Gun class, you would have to make all of the methods the same, unless overrode them for each individual instance of each type of gun. Or you could make a class for every gun and try and keep track of all the method names.

Using an interface, you could make a class for each type of gun and have the exact same methods for every type of gun, but tune each one to your liking for each gun

In theory there is no NEED to use an interface, but it makes your code way easier to follow, as every similar class will have the exact same method names with the exact same end results. Every gun will have gun.shoot() to shoot, gun.reload() to reload. Just makes it more consistent

6

u/tehleel_mir_official Nov 09 '18

now i understand

4

u/TurnupTadpole Nov 09 '18

It took me a while (at least 6 months) to really grasp it. It doesn't do much for you at the entry/educational level, but once you start working on larger projects it's very very nice

4

u/[deleted] Nov 09 '18

You can also store all these guns in a list using the interface type. If you made a handgun class and a machinegun class with no interface then you'll need two lists.

5

u/DrOakman Nov 09 '18

Well explained!

2

u/jameson71 Nov 09 '18

I'm way out of the OOP loop, but way back when I was trying to learn it, I thought the idea would be to make a superclass gun then subclasses for each gun type?

3

u/philipwhiuk Employed Java Developer Nov 09 '18 edited Nov 09 '18

superclass vs interface basically depends on whether there is any common implementation details.

This tends to depend on how the object behaves in your simulation. In general you maximise three distinct things:

  • Code should be as specific as possible. Stuff for reloading for example doesn't need to be in the 'Weapon' class, because I don't reload my Sword.

  • Code shouldn't be repeated. So maybe 'Gun' is worth having, rather than just Weapon, Sword, Glock and AK47.

  • Could should be useful. If my simulation doesn't care about barrel length or stock material, then there's no point modelling that level of detail.

If your weapons are a 'AK47' and 'Flintlock pistol' there may be nothing similar about how the two guns reload. So Gun might be an Interface. If your weapons are an 'AK47' and a 'M4A1', there might be so it becomes an abstract class.

2

u/i_post_things Nov 09 '18

You could, but your abstract class would need to either:

  • Have a bunch of abstract methods that you'd need to implement in your superclass (which is just makes it an interface in disguise)

  • Have a bunch of abstract methods that could make bad assumptions about whatever that method does.

For example, if you make an abstract Gun class, you will create a reload() and some int representing the capacity and then shoot() removes 1 from the capacity.

That's well and nice and all, but you just made a bunch of assumptions that might not work if I make a laser gun where different shots could use fractional amounts of capacity or more than one unit of energy per shot. In order to do that, I now have to override all your methods and make my own energy variable, since it is likely a float and not an integer.

In that case, it might be best to have Gun interface with shoot(), reload() and let whoever implement it however they wish, rather than forcing them to go around overriding all your abstract methods.

All-in-all, you could have the interface, and then create a few abstract classes that implement it (eg, bullet-based guns, laser guns, grenades (eg, no-capacity weapons).

4

u/[deleted] Nov 09 '18

It's funny when I took my first Java position 16 years ago I had the same question. I'd read the books and wondered "why would you ever need that?"

Then I had my "aha moment"

I know this doesn't exactly answer your question. I only do Java development on and off so I'll let others answer. But once you really understand the usefulness of interfaces, a whole world of possibilities opens up.

1

u/tehleel_mir_official Nov 09 '18

yes man i am currently reading Java The Complete Reference book and today was this my topic, i understand all i mean Syntex and other cases ....but but but one question still we we need them....what is the benefit of creating interface when we have abstraction inheritance and simple classes .why why why....

2

u/spikebaylor Nov 09 '18

what is the benefit of creating interface when we have abstraction inheritance and simple classes.

There are a few answers in general but the important one is that java does not allow multiple inheritance. Meaning i cant extend AbstractThingA and also AbstractThingB. I can however extend AbstractThingA and also Implement ThingBInterface and ThingCInterface.

1

u/[deleted] Nov 09 '18

I think you should google for your question, there are lots of results.

4

u/[deleted] Nov 09 '18

Sometimes a conversation is more fun

23

u/desrtfx Out of Coffee error - System halted Nov 09 '18

An interface is both a contract and kind of a super data type.

The interface can be seen as a guarantee that certain methods are implemented.

Just look at the Comparable interface:

The interface declares exactly one method: compareTo

Any class implementing this interface must implement the compareTo method.

Any class/method working with objects that are instances of classes that implement the Comparable interface can rely on the compareTo method being available.

In addition to forming a binding contract, Interfaces can act as super data type since they have the Interface in common.

3

u/tanenbaum Nov 09 '18

To expand: An interface defines a type and implementing it in a class means that the class will have that type in addition to the type it defines itself, as every class does. So you can use the interface as a type when you declare variables or method parameters, but you can never provide the actual interface; it doesn't exist as an object. You provide instantiations of the classes that implement the given interface. In Java, you can declare a variable as a List. However, you can't call new List() on the right side of the declaration as there is no List class; there is only a List interface. You can instead instantiate a variable of the type List as an ArrayList or a LinkedList or something else as these classes implements the List interface.

1

u/[deleted] Nov 10 '18

Why would you do this?

List list = new ArrayList();

Why not just do this instead?

ArrayList list = new ArrayList();

The latter looks cleaner than the former. I don’t understand the point of instantiating a variable whose type is an interface. Why not use the desired class instead?

3

u/Civil_Code Nov 10 '18

There's nothing wrong with that, but in the event you decide to change what collection you want to use you'll have an easier time implementing another List type with the former. At the same time, using List as your reference type means the instantiated object will only have access to the methods that are defined in that type, meaning you can restrict access to some methods in a subclass which aren't known to the parent class.

Mostly it helps simplify messaging where you can pass around the most vague reference type possible to reduce repetitive code

2

u/excitedmelon Nov 09 '18

After 2.5 years in comp science and I just honest to good understood what interface meant (similar to OP, knew what it was in theory, but never really had to use it practically) Thank you!

4

u/Wiqkid Nov 09 '18

The point of an interface is to specify how like-objects should behave.

For example, let's say we have an ATM interface.

All ATM's should have the same functionality, depositMoney(), withdrawMoney(), checkBalance(), etc. All of those methods that are universal to ATMs would be defined in the interface, to guarantee that any ATM using the interface adhered to the defined policy of what ATMs should do. Then, when people make their BankOfAmericaATM, ChaseATM, WellsFargoATM, etc classes, you know that they all have to implement the methods specified in the interface, regardless of their implementation details.

5

u/OffbeatDrizzle Nov 09 '18

That's weird, all of your implementations have randomlyDeductAndChargeOverdraftFee functionality

1

u/[deleted] Nov 09 '18

The benefit is that it allows you to separate the layers of responsibility in your code. It allows you to define a contract for a class before you implement it. If you change the implementation it won’t break anything that depends on the interface as long as the new implementation correctly fulfills the contract.

I often use interfaces when I know what I want a class to do but I don’t want to implement that behaviour right away. It allows me to finish up the logic in the class I’m working on by assuming that the implementation of the contract exists. It’s also great for refactoring logic later.

1

u/Civil_Code Nov 10 '18

One benefit besides those mentioned already is the ease and simplicity in creating an API spec that's able to abstract everything but the generic methods that will be implemented behind the scenes by some other library or driver. Consider JDBC or SLF4J, where the references are all interfaces that can interchangeably switch out MySQL drivers for Postgres, or Log4j2 with Logback, all without changing anything in your own code base.

In your own programs, if you create an abstraction layer that's all interfaces, you could in theory constantly change the logic in your concrete implementations and never need to change a line elsewhere when referencing.

1

u/the_greatest992 Nov 10 '18

Interfaces can extend other interfaces creating a sort of multiple inheritance

-1

u/Ialda Nov 09 '18

You can see it as one way (among others) for enforcing separation of concerns.

2

u/[deleted] Nov 10 '18

[removed] — view removed comment

1

u/tehleel_mir_official Nov 10 '18

ur the one,,, who's answer i understand... thanks thanks a lot