What Is “the Interface” And How Do I Program “Against” It? [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
ArrayList<Class> name = new ArrayList<Class>(#)
Someone told me yesterday that something like this is bad practice, and that I should program “against the interface”, like this:
List<Class> name = new ArrayList<Class>(#)
What did he mean?

ArrayList implements List. So, best to use List for a number of reasons. For example, if you wish to change the type of list (e.g. you decide to use a LinkedList, Stack, or Vector) in the future, you need only change the right side of the assignment and the rest of the code just works, unchanged.

There is no need to reveal what exact implementation of List you're using.
The only methods that are available to you are the methods from the interface. Technically it doesn't matter a lot, but it's a good habit to follow. The code is cleaner and easier to maintain.

The "interface" in that code snippet is List being a more abstract class than ArrayList.
List will be implemented by a number of other classes like ArrayList, LinkedList etc...
By using the interface to declare name, then the users of name do not have to know which type of list name actually is, and if you decide to use a different type of List in future you can without having to change lots of places within your code.

List<Class> name = new ArrayList<Class>(#)
SuperType ref = SubTypeObj
This is polymorphic way of creating an ArrayList. List is a super type of ArrayList.
The advantage of creating the arraylist like this is:
you could later refer the same list to create a LinkedList.
name = new LinkedList(#)

Ideally, you want to use the interface of a collection rather than the implementation for Collection variables and return values. In your example, it's not that big an issue. Where it does become more useful is when writing methods:
public List<String> doSomething() {
}
By using List<String> and not ArrayList<String>, this method could choose a different list to use (it might change to LinkedList for example), but the contract of the API wouldn't change, so all the calling code would still work, even though the method now returns a different type of List.

In Interface defines what methods are available, so when a class is written to implement an interface, it must have the methods defined in the interface. (it may have other methods as well)
Suppose you write a class which other people will use, and it has a method like this:
public void doSomething(List<Thing> aListOfThings) {
//some code to manipulate the list
}
When other people write code to use your class, you don't care exactly what type of List they've used to call your method. All of these are valid:
yourClass.doSomething(new ArrayList<Thing>());
yourClass.doSomething(new AttributeList<Thing>());
yourClass.doSomething(new Vector<Thing>());
yourClass.doSomething(new SomeOtherTypeOfList<Thing>());
They are free to choose whatever type (implementation) of list is suitable for their purposes.

He meant that you should use only the very type of the variable you need. For example, unless you are using methods that are only defined on ArrayList then you should use List. Likewise, if you don't need anything that comes from List then use Collection etc.
There are two reasons for this:
1) It makes it easier in the future to change the implementation to another type. Lets say you are using some ORM that uses a LazilyLoadedList, well if all your code is against List then you can slot it in painlessly. If it is against ArrayList then you need to change lots of method signatures and make sure that you aren't depending on a ArrayList specific methods. This is part of what
2) Interfaces are easier to mock using tools like JMock or Mockito.

This should help you understand what an interface is and how it is useful in software development.
Let's say you need to mail a package to someone. There are many carrier options: USPS, UPS, FedEx, etc.
Now imagine if there was one , central mailbox you could drop your package into and all carriers could deliver from that mailbox. So, you don't care how it gets picked up by USPS, UPS or FedEx. All you need to do is bring your package to the mailbox and drop it off. How it actually gets delivered is irrelevant to you.
In this example, you could have an interface defined as:
public interface IMailService
{
void SendMail(obj myMailObj);
}
And then you could have concrete implementations of MailService defined as:
public class USPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using USPS' implementation
}
}
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
}
public class FedExMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using FedEx's implementation
}
}
Then, when you want to send mail in your code, you would write it like this:
IMailService mailService = new FedExMailService();
mailService.SendMail(myMailObj);
If you later need to use UPS' mail service, then all you'd need to do is instantiate with the UPS type. The rest of the code, including all calls to SendMail() remain unchanged:
mailService = new UPSMailService();
Now, if UPS offers some service that the other carriers do not, then you would need to define the variable as the concrete type.
For example, if the UPS class was defined as such:
public class UPSMailService : IMailService
{
public void SendMail(obj myMailObj)
{
//This code executes SendMail using UPS' implementation
}
//This is a method that only UPS offers
public void SendMailOnSunday(obj myMailObj)
{
//This code executes UPS' proprietary method
}
}
Then your code would need to use the concrete class as such:
UPSMailService mailService = new UPSMailService();
mailService.SendMailOnSunday(myMailObj);

Related

composition-and-forwarding approach for a class with two Lists

I have read Item 16 from Effective Java and
Prefer composition over inheritance? and now try to apply it to the code written 1 year ago, when I have started getting to know Java.
I am trying to model an animal, which can have traits, i.e. Swimming, Carnivorous, etc. and get different type of food.
public class Animal {
private final List<Trait> traits = new ArrayList<Trait>();
private final List<Food> eatenFood = new ArrayList<Food>();
}
In Item 16 composition-and-forwarding reuseable approach is suggested:
public class ForwardingSet<E> implements Set<E> {
private final Set<E> s;
public ForwardingSet(Set<E> s) {this.s = s;}
//implement all interface methods
public void clear() {s.clear();}
//and so on
}
public class InstrumentedSet<E> extends ForwardingSet<E> {
//counter for how many elements have been added since set was created
}
I can implement ForwardingList<E> but I am not sure on how I would apply it twice for Animal class. Now in Animal I have many methods like below for traits and also for eatenFood. This seems akward to me.
public boolean addTrait (Trait trait) {
return traits.add(trait);
}
public boolean removeTrait (Trait trait) {
return traits.remove(trait);
}
How would you redesign the Animal class?
Should I keep it as it is or try to apply ForwardingList?
There is no reason you'd want to specialize a List for this problem. You are already using Composition here, and it's pretty much what I would expect from the class.
Composition is basically creating a class which has one (or usually more) members. Forwarding is effectively having your methods simply make a call to one of the objects it holds, to handle it. This is exactly what you're already doing.
Anyhow, the methods you mention are exactly the sort of methods I would expect for a class that has-a Trait. I would expect similar addFood / removeFood sorts of methods for the food. If they're wrong, they're the exact sort of wrong that pretty much everyone does.
IIRC (my copy of Effective Java is at work): ForwardingSet's existence was simply because you cannot safely extend a class that wasn't explicitly designed to be extended. If self-usage patterns etc. aren't documented, you can't reasonably delegate calls to super methods because you don't know that addAll may or may not call add repeatedly for the default implemntation. You can, however, safely delegate calls because the object you are delegating to will never make a call the wrapper object. This absolutely doesn't apply here; you're already delegating calls to the list.

What is the use of Java virtual method invocation? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I understand what is java method invocation and have practiced many examples using it.
I want to know what is the practical situation or need of this concept.
It would be of great help if anyone could give a real world scenario where it is used and
what would happen if this concept would have not been there?
Here is an example. Suppose we have 2 classes:
class A {
public String getName() {
return "A";
}
}
class B extends A {
public String getName() {
return "B";
}
}
If we now do the following:
public static void main(String[] args) {
A myA = new B();
System.out.println(myA.getName());
}
we get the result
B
If Java didn't have virtual method invocation, it would determine at compile time that the getName() to be called is the one that belongs to the A class. Since it doesn't, but determines this at runtime depending on the actual class that myA points to, we get the above result.
[EDIT to add (slightly contrived) example]
You could use this feature to write a method that takes any number of Objects as argument and prints them like this:
public void printObjects(Object... objects) {
for (Object o: objects) {
System.out.println(o.toString());
}
}
This will work for any mix of Objects. If Java didn't have virtual method invocation, all Objects would be printed using Object´s toString() which isn't very readable. Now instead, the toString() of each actual class will be used, meaning that the printout will usually be much more readable.
OK, I'll try to provide a simple example. You are writing a method that will fill a caller-supplied list:
public void fill(List l) {
list.add("I just filled the list!");
}
Now, one caller wants to use a linked list; another one prefers a list implementation based on an array. There will be other callers with even more list implementations that you've never even heard of. These are totally different objects. Propose a solution that achieves this without relying on virtual methods.
Without virtual methods this would mean that the type List would already need to have the method add implemented. Even if you had a subtype ArrayList which had an overridden method, the compiler (and the runtime!) would simply ignore that method and use the one in List. It would be impossible to use different List implementations that conform to the same interface; it would be impossible to reuse that line of code in the method fill since it would work only with the method in the type List.
So you see, the whole idea of type hierarchy wouldn't make a lot of sense; interfaces and abstract classes couldn't even exist. The whole of Java would break down into shards without that one feature of virtual methods.

Why is the following interface contract not allowed?

I'm thinking about offering a new feature to Java and I would like to ask why have it been restricted by design so far:
public abstract class BodyPart {
abstract public void followBodyPart(BodyPart part);
}
public class Head extends BodyPart{
public void followBodyPart(Body body ) { //Why is this kind of implementation not allowed?
...
}
}
public class Body extends BodyPart{
public void followBodyPart(Head head ) { //and this
...
}
public void followBodyPart(Forearm leftForearm ) { //and also this
...
}
...
}
//Arm, Forearm, etc...
Why is followBodyPart(Body body) in Head not implementing followBody in BodyPart? If it would, the advantages would be clear.
Firstly, the IDE would be able to offer within it's autocomplete feature Body objects as parameters to followBody instead of any other BodyParts objects that Head can not follow.
Secondly, the current version of Body consists of one function and many instanceof's, which could be eliminated.
Finally, generics can help here but not solve the problem, since this code should be ported to Java ME devices.
This question was already asked, in the not appropriate forum as I discovered here
In regards to the answers, I invite you to think different. I understand that anything implementing BodyPart should accept any BodyPart, but: what I want is to be able to say that Head would be able to accept A BodyPart to follow.
Thanks.
The question was also answered in the forum post you linked..
Namely; the interface defines the function should be able to accept anything that implements BodyPart.
By implementing the function in Head to only accept the subclass Body, but not any other subclass; you are violating that contract (since it no longer accepts anything implementing BodyPart).
Interfaces are usually used to provide to "external" code, allowing them to be sure that, whichever implementation of the interface is provided; they can for sure use the functions defined by the interface.
So if this external code gets an BodyPart, it knows it has a function followBodyPart that can accept anything extending BodyPart as argument. That external code will, however, never know that it got Head (or can, after casting it after an instanceof check) and thus cannot know that the interface function will only accept a Body.
By request; say that you provide the BodyPart interface as some kind of program API. In that case, I do not directly need to know what type of BodyPart it is. Now say that I have two of them; received through some functions in your API, for example with the signature: public BodyPart getBody(). The method states it might be a Body I get back; but it could as well be something else (fact is, I don't know!).
According to the BodyPart interface; I can call followBodyPart on the first BodyPart, and pass the second one in as argument. However, the actual Body implementation would not allow this; and there is no way for me to know that.
If you really want different classes to accept different entries; you should either drop the function from BodyPart and just implement it in the subclasses.
By passing those subclasses back from the API; everyone knows what they're talking with, and what it can do (e.g. public Body getBody() and public Head getHead()). Since I then have the actual implementation classes, which have the actual implementation with a certain BodyPart to 'follow', it isn't a problem.
An other option would be - but stated impossible in your question - to use generics; in such case you can define an Interface stating:
public interface Accepts<T extends BodyPart> {
public void followBodyPart(T part);
}
And the API could pass back either the implemented BodyPart, or an Accepts<Head> instance, for example.
(Edit: as I wrote this here, I forgot to keep in mind you cannot implement the same interface more then once with different generic types; so the generic interface method would need the actual implementation to encapsulate objects that can actually handle the calls, making everything even more a mess)
Bonus edit: ofcourse you can also make AcceptsHead, AcceptsArm as interfaces and effectively working around the generics issue :).
I hope this edit clears up why it would be a weird (and bad) idea to have a generic interface (using BodyPart as argument), but only specify specific implementations in the (possibly hidden) implementation classes.
First of all, I'm not quite intuitively understanding your class relationships - they are circular which is already an indication of a bad design. I'm not saying you don't happen to NEED that particular structure - I would just suggest that some refactoring to remove the circularity might ultimately be a better design.
What it looks like you're trying to do is implement a visitor-pattern. But if you have a reference to the base class, it could never trigger the invocation of the specialized methods - e.g. since the compiler can't pick the method you intended, then the runtime is just going to have to do the instance-of switching for you - it would only be syntactic sugar at best (look up scala, they actually do that).
def bodyPart(part:BodyPart) =>
part match {
Head(h) => /* do something with head h */
Foot(f) => /* do something with foot f */
Toe(t) => /* do something with toe t */
}
The other way to solve this is to abstractly noop all possible visitor types:
public class BodyPart { // could have been abstract class
public void followBodyPart(BodyPart part) { }
public void followBodyPart(Head part) { }
public void followBodyPart(Arm part) { }
public void followBodyPart(Foot part) { }
public void followBodyPart(Toe part) { }
}
public class Head { ... /* only implements Head, BodyPart, others error */ }
public class Arm { ... /* only implements Arm, Abdomen, etc */ }
Now the visitor invoker will staticly choose the correct method at compile time. But it needs more plumbing in each implementation because it needs to decide how to properly handle all the other input types. But that's a good thing - it removes ambiguity.

Closure in Java or something like it

I have been trying to find a way to incorporate something similar to Closure in Java 1.6 since I'm developing for Android.
What I want (in a perfect world) I have a class, we will call it "Item".
I then have an arrayList of these.
ArrayList<Item> items = new ArrayList<item>;
In each one of them items.get(x) I want to save a block of code that will be executed when called. This block of code needs to take place in the scope of the class housing the ArrayList items.
My only, half brained idea, would be to create the methods in the class that housed "items" and save the name of the function in each of the "item" instances, then use reflection to call those methods....
I'm pretty doubtful that this could be possible, but this is the place I will find an answer either way.
Thanks ahead of time for any help.
What you need is an interface like
interface Closure{
public void exec();
}
and create an anonymous class for each "closure" code you want
Closure closure = new Closure() {
public void exec(){
// code here
}
}

Why would you declare an Interface and then instantiate an object with it in Java?

A friend and I are studying Java. We were looking at interfaces today and we got into a bit of an discussion about how interfaces are used.
The example code my friend showed me contained this:
IVehicle modeOfTransport1 = new Car();
IVehicle modeOfTransport2 = new Bike();
Where IVehicle is an interface that's implemented in both the car and bike classes.
When defining a method that accepts IVehicle as a parameter you can use the interface methods, and when you run the code the above objects work as normal. However, this works perfectly fine when declaring the car and bike as you normally would like this:
Car modeOfTransport1 = new Car();
Bike modeOfTransport2 = new Bike();
So, my question is - why would you use the former method over the latter when declaring and instantiating the modeOfTransport objects? Does it matter?
There is a big plus on declaring them using the interface, which is what is known as "coding to an interface" instead of "coding to an implementation" which is a big Object Oriented Design (OOD) principle, this way you can declare a method like this:
public void (IVehicle myVehicle)
and this will accept any object that implements that interface, then at runtime it will call the implementation like this:
public void (IVehicle myVehicle)
{
myVehicle.run() //This calls the implementation for that particular vehicle.
}
To answer the original question, why would you use one over the other there are several reasons:
1) Declaring them using an interface, means you can later substitute that value with any other concrete class that implements that interface, instead of being locked into that particular concrete class
2) You can take full advantage of polymorphism by declaring them using an interface, because each implementation can call the correct method at runtime.
3) You follow the OOD principle of code to an interface
It doesn't matter there.
Where it really matters is in other interfaces that need to operate on IVehicle. If they accept parameters and return values as IVehicle, then the code will be more easily extendible.
As you noted, either of these objects can be passed to a method that accepts IVehicle as a parameter.
If you had subsequent code that used Car or Bike specific operations that were used, then it would be advantageous to declare them as Car or Bike. The Car and Bike specific operations would be available for each of the relevant objects, and both would be usable (i.e. could be passed) as IVehicle.
You're really asking: what reference type should I use?
Generally you want to use as general a reference type as possible that still gives you access to the behavior that you need. This means any of the interfaces or parent classes of your concrete type, rather than the concrete type itself. Of course, don't take this point too far -- for example, you certainly don't want to declare everything as an Object!
Consider these options:
Set<String> values1 = new TreeSet<String>();
TreeSet<String> values2 = new TreeSet<String>();
SortedSet<String> values3 = new TreeSet<String>();
All three are valid, but generally the first option of values1 is better because you will only be able to access the behavior of the Set interface, so later you can swap in another implementation quite easily:
Set<String> values1 = new HashSet<String>();
Beware of using the second option values2. It allows you to use specific behavior of the TreeSet implementation in such a way that swapping in a different implementation of Set becomes more difficult. This is fine as long as that's your goal. So, in your example, use a Car or Bike reference only when you need access to something that's not in the IVehicle interface. Be aware though that the following would not work:
TreeSet<String> values2 = new HashSet<String>(); // does not compile!
Still there are times when you need access to the methods that are not in the most general type. This is illustrated in the third option values3 -- the reference is more specific than Set, which allows you to rely on the behavior of SortedSet later.
TreeSet<String> values3 = new ConcurrentSkipListSet<String>();
The question about reference types applies not only where variables are declared, but also in methods where you have to specify the type of each parameter. Fortunately the "use as general a reference type as possible" rule of thumb applies to method parameters, too.
Program to an interface rather than an implementation.
When you program to an interface you will write code that can handle any kind of Vehicle. So in the future your code, without modification, should work with Trains and Planes.
If you ignore the interface then you are stuck with CArs and Bikes, and any new Vehicles will require additional code modifications.
The principle behind this is:
Open to Extension, Closed to Modification.
Because you don't really care what the implementation is... only what it's behavior is.
Say you have an animal
interface Animal {
String speak();
}
class Cat implements Animal {
void claw(Furniture f) { /* code here */ }
public String speak() { return "Meow!" }
}
class Dog implements Animal {
void water(FireHydrant fh) { /* code here */ }
public String speak() { return "Woof!"; }
}
Now you want to give your kid a pet.
Animal pet = new ...?
kid.give(pet);
And you get it back later
Animal pet = kid.getAnimal();
You wouldn't want to go
pet.claw(favorateChair);
Because you don't know if the kid had a dog or not. And you don't care. You only know that --Animals-- are allowed to speak. You know nothing about their interactions with furniture or fire hydrants. You know animals are for speaking. And it makes your daughter giggle (or not!)
kid.react(pet.speak());
With this, when you make a goldfish, the kid's reaction is pretty lame (turns out goldfishes don't speak!) But when you put in a bear, the reaction is pretty scary!
And you couldn't do this if you said
Cat cat = new Cat();
because you're limiting yourself to the abilities of a Cat.
Honestly your argument is rather moot. What's happening here is an implicit conversion to an IVehicle. You and your friend seem to be arguing about whether it's better to do it immediately (as per the first code listing), or later on (when you call the method, as per the second code listing). Either way, it's going to be implicitly converted to an IVehicle, so the real question is -- do you need to deal with a Car, or just a Vehicle? If all you need is an IVehicle, the first way is perfectly fine (and preferable if at a later point you want to transparently swap out a car for a bike). If you need to treat it like a car at other points in your code, then just leave it as a car.
Declaring interfaces and instantiating them with objects allows for a powerful concept called polymorphism.
List<IVehicle> list = new ArrayList<IVehicle>();
list.add(new Car());
list.add(new Bike());
for (int i = 0; i < list.size(); ++i)
list.get(i).doSomeVehicleAction(); // declared in IVehicle and implemented differently in Car and Bike
To explicitly answer the question: You would use an interface declaration (even when you know the concrete type) so that you can pass multiple types (that implement the same interface) to a method or collection; then the behavior common to each implementing type can be invoked no matter what the actual type is.
well interfaces are behaviors and classes are their implementation so there will be several occasions later when you will program where you will only know the behaviors(interface). and to make use of it you will implement them to get benefit out of it. it is basically used to hiding implementation details from user by only telling them the behavior(interface).
Your intuition is correct; the type of a variable should be as specific as possible.
This is unlike method return types and parameter types; there API designers want to be a little abstract so the API can be more flexible.
Variables are not part of APIs. They are implementation details. Abstraction usually doesn't apply.
Even in 2022, it's confusing to understand the true purpose of an interface even to a trained eye who didn't start his/her career in java.
After reading a lot of answers in various online posts, I think that an interface is just a way to not care about the implementation details of a certain activity which is being passed down to a common goal (a certain method). To make it easy, a method doesn't really care how you implement your operations but only cares about what you pass down to it.
The OP is correct in a way to ask why we couldn't just reference to the type of the concrete class than to use an interface. But, we cannot think or understand the use case of an interface in a isolated pov.
Most explanation won't justify it's use unless you look at how classes like ArrayList and LinkedList are derived. Here is my simple explanation.
Class CustomerDelivery {
line 2 -> public void deliverMeMyIphone( DeliveryRoutes x //I don't care how you deliver it){
//Just deliver to my home address.
}
line 3 -> DeliveryRoutes a = new AmazonDelivery();
DeliveryRoutes b = new EbayDelivery();
//sending IPhone using Amazon Delivery. Final act.
deliverMeMyIphone(a.route());
//sending IPhone using eBay Delivery. Final act
deliverMeMyIphone(b.route());
}
Interface DeliveryRoutes {
void route(); // I dont care what route you take, and also the method which takes me as an argument won't care and that's the contract.
}
Class AmazonDelivery implements DeliveryRoutes {
#overide route() {
// Amazon guy takes a different route
}
}
Class EbayDelivery implements DeliveryRoutes {
#overide route() {
// ebay guy takes a different route
}
}
From the above example In line 2, just imagine to yourself what would happen if you cast the type of value x to a concrete class like AmazonDelivery and not the interface DeliveryRoutes type? or what would happen in line 3 if you change the type from the interface to AmazonDelivery type? It would be a mess. Why? because the method deliverMeMyIphone will be forced to work with only one type of delivery i.e AmazonDelivery and won't accept anything else.
Most answers confuse us with by saying Interfaces helps in multiple inheritance which is true, don't get me wrong, but it's not the only story.
With "IVehicle modeOfTransport1 = new Car();", methods owned only by Car are not accessible to modeOfTransport1. I don't know the reason anyway.

Categories