Why shouldn't these interfaces inherit from each other? - java

I posted a question about interfaces and advice I read about in Effective Java. I got the answer I wanted, and all was good, until this afternoon when I signed into SO, and a comment was left saying
These interfaces should not inherit from each other.
I asked why, but still haven't received an answer. Can someone explain why you wouldn't allow these interfaces to inherit? How would you fix it, and still keep the same functionality provided in the answer?
public interface GameObject {
void viewDetails();
}
public interface Weapon extends GameObject {
void attack();
}
//A weapon is not the only item reloadable. A container could be refilled.
public interface Reloadable extends GameObject {
void replenish (final int amount);
}
The only reason I see for these interfaces not to inherit, is the simplicity of the GameObject interface. It isn't providing any functionality that toString can't accomplish. However, it's only the beginning stages of my game, and GameObject will of course expand.

I think you are worried too much about the purity of your design, to the point where you are concerned with trifling details instead of spending your time productively, that is, writing your game.
Either way does not make much of a difference.
Usually, a "GameObject" (and anything whose name ends with "Object") is a class, abstract if need be, but not an interface. The only reason for naming an interface "SomethingObject" is if the interface also extends (or exposes by aggregation) the Closeable (AutoCloseable) interface, meaning that anyone who has a reference to it may destroy it. So, if you take this route, the rest of your questions are answered trivially: interface Weapon may not extend GameObject, because interfaces may not extend classes, and the same goes for Reloadable, and we are done.
Now, if you insist on having a "GameObject" interface, you still have the option of either extending it for every single additional characteristic, or keeping each additional characteristic separate, without extending "GameObject". Both approaches will work.
If you promise, if you swear in the name of everything that is dear to you, that there will never be a Reloadable which is not also a GameObject, then you can go ahead and have Reloadable extend GameObject. But do you really need that? The common practice is that we prefer using interfaces to increase the degree of branching of our inheritance tree, not to turn our inheritance tree into a graph. (Not that it never happens, but it happens very rarely.) So, we usually do not do that. But if you do that, it is not the end of the world.
Also note that when we extend one interface from another, we (not always, but) usually extend the names. So, your Weapon would be WeaponGameObject and your Reloadable would be ReloadableGameObject.
Also note that interface inheritance is rarely, if ever, necessary; you can make Reloadable a free-standing interface (that does not extend GameObject) and you can have Reloadable include a GameObject getGameObject() method, thus essentially linking the two entities together. Then, your BFG9000ReloadableGameObject class may implement both Reloadable and GameObject and implement getGameObject() as return this;

Do a real domain analysis. You'll find that something with replenish behavior, a Replenishable, needn't be a Weapon and may not care while replenishing that it's a GameItem. A Vehicle might also need replenishment. Perhaps something like
public interface Weapon extends GameItem {
public class ChargeGun
implements Replenishable, Weapon {...
public class FlyingCarpet extends GameItem
implements Replenishable, Vehicle {...
It's usually better to have a class do interface mixins than interfaces inherit them. It depends on the domain and how you model it. As much as feasible you want
gun.replenish();
not
replenish(Replenishable Replenishable);
YMMV.

Agreeing with Mike here: Probably not the stage you should be worried about this.
For game development modeling the 'world' using object-oriented principles is often avoided. This is due strong coupling of objects and performance reasons. Very advanced game engines don't create specific classes for entities in the world.
If you are interested in the finer details,
check this out:
http://entity-systems-wiki.t-machine.org/

Related

How to wrap my head around Object Oriented Design

Object oriented design is a pretty neat concept, but I'm struggling on how to wrap my head around most of its facets. I think the key to a good object oriented design is having a good grasp on how to look at it. I usually look at object-oriented this way:
Classes are Real-world entities or objects
Instance Fields are entity's attributes, ('has A')
Methods are like actions, verbs, Entity's abilities
Interfaces are like abilities that you can imbue on an object. It could also be an 'is A or can do' relationship whose implementations are not set in stone. Superman is a Krypton, being a Kryptonian comes with a set of special abilities, like flying, freeze-breath, etc. Superman fly different from Green Lantern and Goku and especially Batman, that is why Flight as interface is probably a good idea if you're creating a Fictional Universe.
public class SuperMan extends Man implements Kryptonian{}
public interface Kryptonian extends Flight, FreezeBreath{
public void fly();
public void coolBreath();
}
Problem comes along when you add Generics into the mix? Because the given type parameters somehow creates a contract between the class/interface and the type.
public interface Flight<T>{
public void fly(T t);
}
In this example, Flight is coupled with a T, T could be a superhero a bird or anything that can fly.But is that really how I should imagine it? Because that seems like the same as what plain interfaces do? Although, a parameterized interface is still an interface, the coupling with the type T is what really bothers me. Moreover, things also get complicated when you add bounded restriction on the parameter type.
public class Pidgey<T extends Bird> implements Flight<T>{}
what real-world concrete object can you identify T with? The above example is pretty wrong, although using the class parameter to also restrict the type of Flight is probably a good design, because Flight is still independent enough that other classes could still use it without any restriction. But the example itself is wrong. Pidgey is a Bird that can fly, but what what could T be? Well, T could be anything, it could be another object or abilities. The question is what are its implications, why put T there? What are real-world examples of doing so?
It's easy to understand when you talk about collections, since collections are like containers. You can create a wide variety of containers that holds different kinds of objects.
public class WaterBottle<T extends Liquid> implements UniqueCap{}
But I've seen Generics being used not just on a container-like objects? How could one design such objects, what did they consider?
Your analogies to the various features in OOP are definitely valid. Generics definitely make the most sense when talking about collections/containers/Hashmaps. They do have their uses in other places, though. For example, if a bank wants to process notes in many currencies, they can write
public class moneyProcessor
However, generics aren't required. In the context of your Flight interface, there wouldn't be much of a reason to use generics. Which brings me to another point:
Just because someone else does something one way doesn't mean you have to do it that way. OOP is very flexible for a reason. There's always more than one correct way. If a method takes an Object as a parameter, it's not the end of the world. Just make sure you can read it later. :)
Edit: and that others can read it too.
Its convention to use T when dealing with generics. it makes code readable as others reading your code will immediately know you're referring to a generic and nothing specific

Java Code Style -- Interfaces vs. Abstract Classes

A new collaborator of mine who was reviewing some code I'd written told me that she wasn't used to seeing interfaces used directly in Java code, e.g.:
public interface GeneralFoo { ... }
public class SpecificFoo implements GeneralFoo { ... }
public class UsesFoo {
GeneralFoo foo = new SpecificFoo();
}
instead, expecting to see
public interface GeneralFoo { ... }
public abstract class AbstractFoo implements GeneralFoo { ... }
public class SpecificFoo extends AbstractFoo { ... }
public class UsesFoo {
AbstractFoo foo = new SpecificFoo();
}
I can see when this pattern makes sense, if all SpecificFoos share functionality through AbstractFoo, but if the various Foos have entirely different internal implementations (or we don't care how a specific Foo does Bar, as long as it does it), is there any harm in using an interface directly in code? I realize this is probably a tomato/tomato thing to some extent, but I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing.
If you have no need for an abstract class with certain details common to all implementations, then there's no real need for an abstract class. Complexity often gets added to applications because there is some perceived need to support future features that haven't yet been defined. Stick with what works, and refactor later.
No, she's inexperienced, not right. Using interfaces is preferred, and writing redundant abstract super classes for the sake of redundancy is redundant.
UsesFoo should care about the behaviour specified by the interface, not about the super class of its dependencies.
For me "she wasn't used to" is not good enough reason. Ask her to elaborate on that.
Personally I'd use your solution, because:
AbstractFoo is redundant and ads no value in current situation.
Even if AbstractFoo was needed (for some additional functionality), I'd always use lowest needed type: if GeneralFoo was sufficient, then I'd use that, not some class derived from it.
It depends only on your problem.
If you use interfaces only, then if all your classes have a same method, it would have to be implemented redundantly (or moved away to a Util class).
On the other hand, if you do write an intermediary abstract class, you solved that problem, but now your subclass may not be a subclass of another class, because of absence of multiple inheritance in Java. If it was already necessary to extend some class, this is not possible.
So, shortly - it's a trade off. Use whichever is better in your particular case.
There is not harm in directly using an interface in code. If there were, Java would not have interfaces.
The disadvantages of using an interface directly include not being able to reach and class-specific methods which are not implemented in the interface. For poorly written interfaces, or classes which add a lot of "other" functionality, this is undesirable as you lose the ability to get to needed methods. However, in some cases this might be a reflection of a poor design choice in creating the interface. Without details it is too hard to know.
The disadvantages of using the base class directly include eventually ignoring the interface as it is not frequently used. In extreme cases, the interface becomes the code equivalent of a human appendix; "present but providing little to no functionality". Unused interfaces are not likely to be updated, as everyone will just use the base abstract class directly anyway. This allows your design to silently rot from the viewpoint of anyone who actually tries to use the interface. In extreme cases, it is not possible to handle an extending class through the interface to perform some critical functionality.
Personally, I favor returning classes via their interface and internally storing in members them via their lowest sub-class. This provides intimate knowledge of the class within the class's encapsulation, forces people to use the interface (keeping it up-to-date) externally, and the class's encapsulation allows possible future replacement without too much fuss.
I'm curious if there's an advantage to the second style, or disadvantage to the first style, that I'm missing
That reasons for the first interfaces style:
Often, the design is such that the interface is the public interface of the concept while the abstract class is an implementation detail of the concept.
For example, consider List and AbstractList in the collection framework. List is really what clients are usually after; fewer people know about about AbstractList because its an implementation detail to aid suppliers (implementers) of the interface), not clients (users) of the class.
The interface is looser coupling, therefore more flexible to support future changes.
Use the one that more clearer represents the requirement of the class, which is often the interface.
For example, List is often used rather than AbsrtactList or ArrayList. Using the interface, it may be clearer to a future maintainer that this class needs some kind of List, but it does not specifically need an AbstractList or an ArrayList. If this class relied on some AbstractList-specific property, i.e. it needs to use an AbstractList method, then using AbstractList list = ... instead of List list = ... may be a hint that this code relies on something specific to an AbstractList .
It may simplify testing/mocking to use the smaller, more abstract interface rather than to use the abstract class.
It is considered a bad practice by some to declare variables by their AbstractFoo signatures, as the UsesFoo class is coupled to some of the implementation details of foo.
This leads to less flexibility - you can not swap the runtime type of foo with any class that implements the GeneralFoo interface; you can only inject instances that implement the AbstractFoo descendant - leaving you with a smaller subset.
Ideally it should be possible for classes like UsesFoo to only know the interfaces of the collaborators they use, and not any implementation details.
And of course, if there is no need to declare anything abstract in a abstract class AbstractFoo implements GeneralFoo - i.e. no common implementation that all subclasses will re-use - then this is simply a waste of an extra file and levels in your hierarchy.
Firstly I use abstract and interface classes plentifully.
I think you need to see value in using an interface before using it. I think the design approach is, oh we have a class therefore we should have an abstract class and therefore we should have interfaces.
Firstly why do you need an interface, secondly why do you have an abstract class. It seems she may be adding things, for adding things sake. There needs to be clear value in the solution otherwise you are talking about code that has no value.
Emperically there you should see the value in her solution. If there is no value the solution is wrong, if it cant be explained to you she does not understand why she is doing it.
Simple code is the better solution and refactor when you need the complexity, flexibility or whatever perceived value she is getting from the solution.
Show the value or delete the code!
Oh one more thing have a look at the Java library code. Does that use the abstract / interface pattern that she is applying .. NO!

Explaining Interfaces to Students [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
For a few years I was a teaching assistant for an introduction to programming module - Java for first year undergraduates.
Mostly it went well and we managed to get object-oriented programming across to the students quite well, but one thing that students rarely saw the point of was interfaces.
Pretty much any explanation we gave either came across as too contrived to be useful for learning, or too far removed from their position as beginners. The reaction we tended to get was "I... see," translated as "I don't understand and they don't sound useful".
Anyone here have a way of successfully teaching students about interfaces? I'm not a teaching assistant any more, but it's always nagged at me.
If you are trying to explain it to beginners I would stick with the idea that interfaces can promote code reuse and modularity within the code:
For example lets say we are going to paint some objects:
public class Painter {
private List<Paintable> paintableObjects;
public Painter(){
paintableObjects = new ArrayList<Paintable>();
}
public void paintAllObjects(){
for(Paintable paintable : paintableObjects){
paintable.paint();
}
}
}
public interface Paintable {
public void paint();
}
Now you could explain to the students that without Paintable interface the Painter object would need to have methods to paint certain types of objects, like a method called paintFences() and paintRocks() and we would need to have a new Collection for each type of objects we want the painter to be able to paint.
But thankfully we have interfaces which make painting objects a breeze and how objects are painted is left entirely up to classes that implement the Paintable interface.
EDIT
Another benefit that I forgot to mention is that if you ever need to add new object to paint to your code base, all you need to do is create a new class that implements Paintable and the Painter class never has to change. In this sense the Painter class is never dependent upon the objects it is going to paint, it only needs to be able to paint them.
EDIT 2
James Raybould reminded me of a key use of interfaces I forgot to mention: Having an interface between your components, like the Paintable objects and Painter objects, allows you to more easily develop with other people. One developer can work on the Painter objects and another can work on the Paintable objects and all they have to do to function properly together is define a common interface beforehand that they will both use. I know when I've worked on projects with other people in college level projects its really helpful when you are trying to have everyone work on different parts of the project and still have all components come together nicely in the end.
In explaining interfaces and object oriented concepts in general to non-programmers, I always use the home entertainment system analogy.
The DVD player, TV, Cable Box, Remote Control are all objects that encapsulate complicated and sophisticated functionality. However, they have interfaces to each other and to the Humans that operate them that largely hide the lion share of that complexity.
The video in jack of a TV is an interface that is implemented by the DVD player and the cable box and a number of other types of devices.
I suspect it would be possible and perhaps an educational exercise for a student to describe their own home entertainment system entirely using Java code.
"Where classes ARE something, typically interfaces DO something. So I might have a car, but I would never go "carring" but I might go driving... so my Car might implement "drivable" interface."
EDIT:
Mark brings up a good point. Interfaces don't do anything at all, but instead define what behaviors happen. And, he also brings up a good point about not wanting to confuse the audience. Not that it's okay to confuse seasoned developers, but it's definitely not a good idea to confuse a brand new student. In light of this, I'm revising my one-liner into a many-liner.
"Where classes define existence, interfaces define behavior. Classes define what something is, while interfaces define what something does. So I might have a car, and it has things like an Engine, how much gas it has, what it's historic MPG is, and the like, but I would never go "carring". I might, on the other hand, go Driving... can my Car drive? It can if I give it a Drive method. I can also have "Driveable" interface with a drive method, and leave it up to the car to determine what driving really means. Now, if I only have cars it's not a big deal to have an interface. But what about trucks? If they both are Drivable, I can simply have a List<Drivable for both of them. Of course, the observant student says "Why can't Car and Truck both simply extend Vehicle, with an abstract Drive method?" Which, actually is a very valid notion. But, what about the Space Shuttle? Very few of the components between Car and Truck apply to the Space Shuttle, so it doesn't seem well suited to extend the Vehicle class. Or what about future cars? We have no idea what they might be like, they might not have chassises, they might just be bubbles of energy that move us around, but we might still call their behavior drive()."
breathes
Now that paragraph/essay is a little verbose, but I could see, with some slides or a chalkboard, being effective for first year students to get their head around (assuming they understand abstract classes first anyway).
Well I just explained interfaces to a work partner, she was learning java from progress and she really did not get all the OOP stuff at the beginning so I just explained everything from a non-software engineering point of view, my explanation for interfaces where something like this:
Suppose you want to hire a plumber to fix some things on your house, you don't know (and you don't care much) who you may end up hiring but you know what the plumber must be able to do. So, you define a set of tasks that anyone that claims to be a plumber must know how to do. Of course everybody might have its own way of carrying out each task, but in the end, the person you are hiring is a plumber because they know how to do each task. So, if you were to write this in java, the first thing to do would be to define an interface plumber like this:
public interface Plumber
{ //silly code here }
OK then, let's say that I know how to do each task you are requesting for and so I'm fully compliant with your requirements and so according to you I'm a plumber. So, today I decide to be your plumber and you decide to hire me (yay!), based on the last example, you can say that I'm a person that knows how to develop software and plumbing in a specific way, if I were to write code for me as a class I could write something like this:
public class Rick extends Person implements SoftwareDeveloper, Plumber
and later you could fix things in your house using me as your plumber:
Plumber thePlumber = rick;
thePlumber.fixLeak(myHouse.bathroom.leak) // =(
from this point on, the remaining OOP concepts were easy to explain.
Well, recently, I happened to explain this to someone close. The way I explained the question "why Interfaces?", is by taking example of of the USB Port and the USB drives.
The USB port can be considered as a specification, and any USB drive can fit into it, provided they implement the specification. So in this case, the port becomes the Interface and the numerous types of USB sticks available, become the class.
Carrying this example ahead, if I were to supply someone an USB drive (class), I would not need to tell them (the calling method) as to what am I passing across. Had the calling method taken a USB drive (class type) as a reference, I would not have been able to pass any but only the USB drive that the port is meant for.
To sum it up, Intefaces, help the caller be comptabile with the calling method (in a use-case when the calling method expects an instance of a particular type), no matter what instance you pass across, the caller as well as the callee are sure that it (instance) would fit into the Interface reference (the USB port for analogy).
Class, we spent the last few sessions implementing quicksort. It was difficult to sort that list of Persons by name. What would you now do, if you had to sort this list by grade? And what would you do if you had to sort a list of dinousaurs by age? The only way you know so far is to copy the code of the quicksort, and change the comparison and the types it operates on. That would work - until you find that elusive bug that always plagued your quicksort, and had to fix it in several dozen copies of that quicksort scattered all over the place.
Today, we are going to learn a better way.
We can write a quicksort without defining the order we want to sort the list into, and define that order (and only that order) separately when we invoke that quicksort.
[ insert explanation of the mechanics of interfaces and polymorphism, using the Comparator interface as example, here ]
Now, there is only a single copy of quicksort, and bugs only have to be fixed once. Also, people can use quicksort without understanding it (or if they have understood it, without thinking about its mechanics whenever you want to sort something). Also, the people writing the quicksort did not need to know the order you need your list sorted. So the interface isolated the two groups of programmers, allowing them to develop their parts of the software in isolation. This is why, in many programming languages, you will find well implemented and tested sort methods in the api, even though the programmers of these methods could not know all the types of objects and orders people want to sort into later.
I usually use "contract" but "promises solemnly to provide" might also help understanding.
I recommend the first chapter of Head First Design Patterns for this. The Duck simulation explains the problem with using inheritance, and the rest of the chapter goes on explaining how to do it.
This explains best : (referenced from this tutorial)
There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
For example, imagine a futuristic society where computer-controlled robotic cars transport passengers through city streets without a human operator. Automobile manufacturers write software (Java, of course) that operates the automobile—stop, start, accelerate, turn left, and so forth. Another industrial group, electronic guidance instrument manufacturers, make computer systems that receive GPS (Global Positioning System) position data and wireless transmission of traffic conditions and use that information to drive the car.
The auto manufacturers must publish an industry-standard interface that spells out in detail what methods can be invoked to make the car move (any car, from any manufacturer). The guidance manufacturers can then write software that invokes the methods described in the interface to command the car. Neither industrial group needs to know how the other group's software is implemented. In fact, each group considers its software highly proprietary and reserves the right to modify it at any time, as long as it continues to adhere to the published interface.
More Link: http://download-llnw.oracle.com/javase/tutorial/java/concepts/interface.html
Understanding interfaces is not very different to understanding polymorphism and IS-A relationships. All classes implementing the same interface can be manipulated uniformly by the program as the "base" type because of the relationship established by implementing an interface or inheriting a base class.
The choice between an interface and a base class is a design decision. I'd keep this simple.
Define a class when your implementation can assume the complete or partial behavior of a class.
Make that class abstract to indicate the base class is not a complete implementation and cannot be used as is.
Provide an interface instead of a base class if it does not make sense to provide a partial implementation.
The benefits of interfaces and inheritance are pretty much the same. An interface is simply a more abstract definition of a type than a base class is.
Update
Here's a simple program you could use to demonstrate how similar inheritance and interfaces are. Modify the program to make Base an interface instead of a class. In ClassA, replace "extends" for "implements". The program's result will be the same.
The purpose of ClassB is to illustrate further illustrate the importance of the relationship between a class and its interface/base class. An instance of ClassB may not be passed to processBase in spite of its similarities with Base, unless we establish an explicit relationship.
abstract class Base {
public void behavior() {};
};
class ClassA extends Base {
public void behavior() {
System.out.println("ClassA implementation of Base behavior");
}
};
class ClassB {
public void behavior() {
System.out.println("ClassB's version of behavior");
}
}
public class InterfaceExample {
public void processBase (Base i) {
i.behavior();
}
public static void main (String args[]) {
InterfaceExample example = new InterfaceExample();
example.processBase(new ClassA());
}
}
Interface Oriented Design describes this better than I ever could http://pragprog.com/titles/kpiod/interface-oriented-design. The author uses some excellent examples of interfaces versus inheritance for things like the taxonomy of the animal kingdom. It has some of the best arguments against excessive inheritance and judicious use of interfaces I have read to date.
A bunch of websites with incompatible ways of bringing them up:
Listing of Facebook.java:
public class Facebook {
public void showFacebook() {
// ...
}
}
Listing of YouTube.java:
public class YouTube {
public void showYouTube() {
// ...
}
}
Listing of StackOverflow.java:
public class StackOverflow {
public void showStackOverflow() {
// ...
}
}
A client manually handling the different methods the websites use to bring
themselves up:
Listing of ClientWithoutInterface.java:
public class ClientWithoutInterface {
public static void main(String... args) {
String websiteRequested = args[0];
if ("facebook".equals(websiteRequested)) {
new Facebook().showFacebook();
} else if ("youtube".equals(websiteRequested)) {
new YouTube().showYouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
new StackOverflow().showStackOverflow();
}
}
}
Introduce a Website interface to make the client's job easier:
Listing of Website.java:
public interface Website {
void showWebsite();
}
Listing of Facebook.java:
public class Facebook implements Website {
public void showWebsite() {
// ...
}
}
Listing of YouTube.java:
public class YouTube implements Website {
public void showWebsite() {
// ...
}
}
Listing of StackOverflow.java:
public class StackOverflow implements Website {
public void showWebsite() {
// ...
}
}
Listing of ClientWithInterface.java:
public class ClientWithInterface {
public static void main(String... args) {
String websiteRequested = args[0];
Website website;
if ("facebook".equals(websiteRequested)) {
website = new Facebook();
} else if ("youtube".equals(websiteRequested)) {
website = new YouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
website = new StackOverflow();
}
website.showWebsite();
}
}
Whoop-de-doo, more code for nothing? Actually we can go a little further and
have the client rope a couple of friends into helping it find and render a
requested website:
Listing of ClientWithALittleHelpFromFriends.java:
public class ClientWithALittleHelpFromFriends {
public static void main(String... args) {
WebsiteFinder finder = new WebsiteFinder();
WebsiteRenderer renderer = new WebsiteRenderer();
renderer.render(finder.findWebsite(args[0]));
}
}
Listing of WebsiteFinder.java:
public class WebsiteFinder {
public Website findWebsite(String websiteRequested) {
if ("facebook".equals(websiteRequested)) {
return new Facebook();
} else if ("youtube".equals(websiteRequested)) {
return new YouTube();
} else if ("stackoverflow".equals(websiteRequested)) {
return new StackOverflow();
}
}
}
Listing of WebsiteRenderer.java:
public class WebsiteRenderer {
public void render(Website website) {
website.showWebsite();
}
}
Looking back at ClientWithoutInterface, it is totally coupled to both specific lookup and rendering based. It would be very difficult to manage when you get to hundreds or thousands of sites. With the Website interface in place the WebsiteFinder could easily be converted to be backed on a Map, a database or even a web based lookup to satisfy increasing scale.
Interfaces make it possible to separate a role from the component that achieves it. They make it possible to swap in alternative solutions to the same problem based on pretty much anything:
Current load on machine
Size of the data set (sorting algorithms can be picked)
User requesting the action being performed
I was typing this as a comment to Harima555s answer, but it expanded. I wondered if it makes more sense to start at the other end - give them a feel for how interfaces are useful, before going into how you write one.
Presuming they have a good grasp of inheritance, polymorphism and abstract classes. I would probably start with a recap on abstract classes, by asking one of the students to explain them.
Next, introduce an example of classes with interfaces to get over the concept of roles / contracts. To simplify things, start with a single superclass.
public class Rick extends Person implements SoftwareDeveloper, Plumber
public class Zoe extends Person implements SoftwareDeveloper, Chef
public class Paul extends Person implements Plumber, Chef
public class Lisa extends Person implements Plumber
Don't explain it too much, but try and get the student to work through what the syntax might mean - perhaps showing some code that references a Plumber or SoftwareDeveloper.
Ask them how they would achieve the same thing using inheritance from Person. They should get stuck quite quickly, or come up with multiple inheritance. To avoid discussing the diamond problem until later, say there are no overlapping methods in the roles.
Next I'd try to get over the idea that the same interface can be used on different types of Class.
public class Plane extends Vehicle implements Fly, PassengerTransport, Serviceable
public class Train extends Vehicle implements PassengerTransport, Serviceable
public class Bird extends Animal implements Fly
Again, try to get them to consider how they could implement the same thing using a common superclass and overrides.
Then illustrate how you would write polymorphic code using the interface rather than class - say a TravelAgent who sells tickets for a PassengerTransport. Dwell on the strength of this - that you can write polymorphic code that works on Classes from different hierarchies.
At this point, they should probably be under the illusion that an interface is a pretty much like being able to add another superclass to a class, and will have grasped the advantages of multiple inheritance.
So now we have to explain why that complicates things, and interfaces have no default implementation, via understanding the diamond problem.
Go back to the first example, get them to work through what happens if SoftwareDeveloper and Plumber both have a 'MakeDrink' method (one makes Cola, the other makes Coffee) and we execute MakeDrink on Rick.
Try and nudge someone towards considering the idea that if MakeDrink is kept abstract in both 'superclasses' the problem goes away. At this point, having got the conceptual side, we should be ready to cover the syntax for defining an interface.
(I did consider introducing the second reason - the difficulty of writing generic code that could be applied to different class hierarchies, but found that you end up with 'well why can't you inherit an altitude attribute from the interface' or discussing generic programming too early).
I think by now we should have covered the concepts via the mickey mouse examples - and you could then go back through explaining the correct technical terminology, and use real-world examples from the Java API.
I wouldn't want to confuse people while they are trying to learn Java/Interfaces, but once they've got it, it may be worth pointing out that other OO languages take different approaches to the same problem, from multiple inheritance to duck-typing - and if they are interested they should research them.
Do you teach JDBC as well? Take it as an example. It's an excellent real world example of how powerful interfaces are. In JDBC you're writing code against an API which exist of almost only interfaces. The JDBC driver is the concrete implementation. You can easily reuse the JDBC code on many DB's without rewriting the code. You just have to switch the JDBC driver implementation JAR file and driver class name to get it to work on another DB.
At least, using interfaces offers you the possibility to change from the concrete implementation (the code logic which is responsible for the behaviour) at some way/point without rewriting the whole code. Try to use real world examples when explaining things. It would make more sense.
Well, I found lately a very useful method of using interface.
We have many objects...
public class Settings { String[] keys; int values; }
public class Car { Engine engine; int value; }
public class Surface { int power; int elseInt; }
// and maaany more (dozens...)
Now, someone is creating (i.e.) table and want to show some of objects from the list of all objects, but to show objects in the list he must write method that returns String[].
String[] toArrayString()
So he just implements this method in all classes that he need to in table
public class Settings { String[] keys; int values; public String[] toArrayString {...} }
public class Car { Engine engine; int value; } // THIS NOT
public class Surface { int power; int elseInt; public String[] toArrayString {...} }
// and maaany more (dozens...)
Now, when he creates table he is writing smth like this
public void createTable() {
for(Object obj : allObjects) {
if(obj instanceof Settings) {
Settings settings = (Settings)obj;
table.add(settings.toArrayString());
}
if(obj instanceof Surface) {
// cast...
}
// etc multiple times...
}
}
With interface this code can be much shorter and easier to read and maintain:
public interface ISimpleInterface { String[] toArrayString; }
public class Settings implements ISimpleInterface { String[] keys; int values; public String[] toArrayString {...} }
public class Car { Engine engine; int value; } // THIS NOT
public class Surface implements ISimpleInterface { int power; int elseInt; public String[] toArrayString {...} }
public void createTable() {
for(Object obj : allObjects) {
if(obj instanceof ISimpleInterface) {
ISimpleInterface simple = (ISimpleInterface)obj;
table.add(simple.toArrayString());
}
}
}
Moreover, we can implement multiple interfaces in a very clean and effective way without any derivation (derivation is sometimes impossible and not only in case, when class is using some kind of other derivation already).
Interfaces provide a look at what a class needs to do for instance you can have an Animal interface and lets say that has a method called speak(), well each animal can speak but they all do it differently but this allows you to cast anything that implements animal to animal so you can have a List of animals and make them all speak but use their own implementation. Interfaces are simply wrappers for these kinds of things.
In this previous question there are some good scenarios that explain the whys behind the use of interfaces.
Stack Overflow Question
The real value of interfaces comes with being able to override components in 3rd party APIs or frameworks. I would construct an assignment where the students need to override functionality in a pre-built library that they cannot change (and do not have the source for).
To be more concrete, let's say you have a "framework" that generates an HTML page implemented as a Page class. And page.render(stream) generates the html. Let's say that Page takes an instance of the sealed ButtonTemplate class. The ButtonTemplate object has its own render method so that in page.render(stream) buttonTemplate.render(label,stream) gets called anywhere there is a button and it produces the html for a submit button. As an example to the students, let's say that we want to replace those submit buttons with links.
I wouldn't give them much direction other than describing the final output. They will have to pound their heads trying various solutions. "Should we try to parse out the button tags and replace with anchor tags? Can we subclass ButtonTemplate to do what we want? Oh, wait. It's sealed! What were they thinking when they sealed this class!?!" Then after that assignment show a second framework with the ILabeledTemplate interface with the render(label,stream) method.
In addition to the other answers, you could try explaining it from a different perspective. The students I'm sure already know about inheritance because it is jammed down the throats of every Java student from probably lecture one. Have they heard about multiple inheritance? Method resolution was seen as a design issue in C++ (and also in Perl and other multiple-inheritance languages) because conceptually it's ambiguous as to exactly what should happen when a method is called in a subclass that is defined in two of its base classes. Are both executed? Which one goes first? Can one be referenced specifically? See also the diamond problem. It's my understanding that this confusion was resolved simply by introducing interfaces, which have no implementation, so there's no ambiguity as to which implementation to use during method resolution.
If a class needed to handle exactly one piece of abstract functionality, and didn't need to inherit any other class, one could use an abstract class to expose the functionality and then derive the real class from that. Notice the two items in italics, however. Interfaces make it possible for a class to behave as several independent types of abstract things, even if the class is derived from another class that does not behave as those types of things. Thus, interfaces satisfy one of the main usage cases for multiple inheritance, without the ickiness that goes along with multiple inheritance.
A simple real-world example of a very practical interface: iEnumerable. If a class holds some arbitrary number of some type of item, is is very useful for another class to act upon all of those item without having to worry about the particulars of the object that holds them. If "enumerableThing" were an abstract class, it would be impossible for an object of any class which derived from something that wasn't an "enumerableThing" to be passed to code that expected an enumerableThing. Since any class, including derived classes, can implement enumerableThing without regard for whether the base classes do so, it's possible to add enumeration ability to any class.
A long time ago, I read a book (can't remember the name of it though) and it had a pretty good analogy for interfaces. If you (or your students) ever went to a Cold Stone Creamery ice cream store, this will sound kind of familiar. Cold Stone has ice cream and with the ice cream you can add several different things to the ice cream (called mix-ins at Cold Stone). These mix-ins would be analogous to interfaces. Your class (or ice cream) can have as many interfaces (or mix-ins) as you want. Adding an interface (or mix-in) will add the contents (or flavor) of that interface (or mix-in) to your class (or ice cream). Hope this helps!
Contracts are first things that are taught about interfaces but they are built in the language to provide the skills of multiple inheritance and avoid the complexity of multiple inheritance.. So you can teach them that interfaces add runtime behaviour to programs, or you can tell the students that interfaces can be used to change runtime behaviour of objects..
First, the students must grasp the concept of abstractions.
When you (you == the students) see a teacher, you can describe him as a teacher...
You can also describe him as an employe (of the school).
And you can describe him as a person.
You will be right the three times. Thoses are "titles" you can give him.
He is a teacher, a computer science teacher, in the same way a math teacher is a teacher.
They are on the same level of abstraction.
Now a teacher is an employee, in the same way a janitor is an employee.
They are on the same level of abstraction.
An employe is a person, in the same way an unemployed person is a person.
They are on the same level of abstraction.
(Draw the whole thing on the board in a UML kinda way).
And that's the architecture that will describe (roughly) the position of a science teacher in society.
Now the levels of abstraction define what a common group of objects have in common : All the teachers teach to their students and create impossible exam questions to make sure they fail. All the school's employes work for the school.
In programming, an interface is a level of abstraction. It describes the actions that a group of objects can accomplish.
Each object has a unique way of doing the action, but the type of action is the same.
Take a few music instruments for example : A piano, a guitar and a flute.
What do they have in common ? A musician can play them.
You can't ask a musician to blow in the 3 instruments but you can ask him to play them.
The architecture of the whole concept will be the following:
The Interface (what they have in common) is Instrument. Because they're all instruments : it's an abstraction they all have in common.
What can they do in common ? Play. So you define an abstract method called Play.
Now you can't define how the "Instrument" will play because it depends on the type of instrument.
Flute is a type of Instrument. So the class Flute implements Instrument.
Now you must define what the musician will do when he plays that type of instrument.
So you define the play method. This definition will override the definition of the Instrument.
Do the same with the 2 others instruments.
Now if you have a list of instruments but don't know what type they are, you can still "ask" them to play.
Each flute will be blown.
Each guitar will be scratched.
Each pianio will be ... huh... pianoted ? whatever !
But each object will know what to do to execute the action "Play". You don't know what kind of instrument they are, but since you know they are instruments, you ask them to play and they know how to do that.
You may also want to compare and contrast interfaces in Java with C++ (where you end up using multiple inheritance and/or "friend" classes).
(At least, to me, that showed me how much simpler/easier interfaces were in Java :-)
I would tell them "Interfaces define what behaviors are provided" and "Implementations provide those behaviors". A piece of code that uses an interface doesn't need the details of how things are happening, it only needs to know what things can happen.
A good example is the DAO pattern. It defines behavior like "save", "load", "delete". You could have an implementation that works with a DB, and an implementation that goes to the file system.
I think a lot of the other answers so far are too complicated for students who don't get it right away...
I think in general, hands-on learning always helps reinforce concepts after lectures and examples. So in the same vein as meriton suggests, I would present two versions of the same program. (quicksort is a good example)
Have the students modify each program several times, unveil subtle bugs in the program for them to fix. Your students will soon find, I think, that interfaces provide many advantages when designing a program when they're the ones who have to modify it later!
I always think of it as a mean to (verbally) communicate as little as possible because that (good communication) is the most difficult thing in software engineering. Same for Web Services and SOA. If you give somebody an interface and say "Please provide me this service." it is a very convenient way because you don't have to explain a lot, and the compiler will check if they did a proper job, instead of you! (I mean, not really but at least it'll ensure the methods are there).

Use of Java [Interfaces / Abstract classes] [duplicate]

This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
Lately i decided to take a look at Java so i am still pretty new to it and also to the approach of OO programming, so i wanted to get some things straight before learning more, (i guess it's never to soon to start with good practices).
I am programming a little 2D game for now but i think my question applies to any non trivial project. For the simplicity I'll provide examples from my game.
I have different kinds of zombies, but they all have the same attributes (x, y, health, attack etc) so i wrote an interface Zombie which i implement by WalkingZombie, RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an abstract class? Or with a super class? (I am not planning to partially implement functions - therefor my choice for an interface instead of an abstract class)
I have one class describing the main character (Survivor) and since it is pretty big i wanted to write an interface with the different functions, so that i can easily see and share the structure of it. Is it good practice? Or is it simply a waste of space and time?
I hope this question will not be rated as subjective because i thought that experienced programmers won't disagree about this kind of topic since the use of interfaces / super classes / abstract classes follows logical rules and is thereby not simply a personal choice.
You can think of an interface as a "contract". You are defining a set of methods that classes which implement this interface must implement.
An abstract class, on the other hand, is used when you have some code that could be common to all the child classes you want to implement. So you might have an abstract class called Shape that has some common code, and in your derived classes (Circle, Square, etc.) you could have the code that is specific to those shapes (getArea would be an example). But something like color might be common to all shapes, so you could put a getColor method in your Shape abstract class.
And you can combine the two ideas. You can have abstract classes which implement interfaces, and this gives you the best of both worlds.
These concepts are used over and over again in OO, so it's important to understand them. You seem to be well on your way :).
So if your zombie class has some common behavior that applies to all types of zombies, it sounds like a good candidate to be an abstract class. You could also consider creating an interface (maybe a GameCharacter interface) if you have other characters in your game (maybe UndeadMice or something :)). Then your Zombie abstract class and UndeadMouse abstract class would implement the GameCharacter interface.
When in doubt, I choose to follow the GOF paradigm.
Encapsulate what varies: - Define unique behavior in its own class. To refer the above example, implement behaviors for walking, running and teleportation in its separate class. This way, polymorphic behavior is implemented.
Conversely, **Aggregate what is common** - Use Abstract classes to define common behavior in polymorphic associations. I use these principles when designing relationships between objects.
Yes, I think you're heading down the right track with interfaces over abstract classes.
Any concrete Zombie you might want to make could possess any combination of the Walking, Running or Teleporting features you care to implement.
I think modern programming theory discourages inheritance as much as possible, because it inhibits reusability and flexibility in the long-run. Rather, use interfaces and composition to achieve flexibility without 'tight coupling'.
One methodology to re-use code without inheritance, you could apply the 'Favour composition over inheritance' paradigm.
I like to think Josh Bloch's 'Effective Java' (2nd edition) can be taken as "current thinking" ...
http://books.google.com/books?id=ZZOiqZQIbRMC&pg=RA1-PA71&lpg=RA1-PA71&dq=%22Bloch%22+%22Effective+java:+programming+language+guide%22+&hl=de&sig=RxlDlRBWUvNAzsAFzqOcftrYI5E#v=onepage&q&f=false
So, you could implement all your behaviours as independent classes, and then give each zombie implementation its own combination of behaviours, through implementation & composition..
Hope that makes sense & helps ...
I would have written Zombie as an abstract class to avoid the redefinition of the fields x, y, health, etc...
For the Survivor class, I would simply have declare public the functions to be used externally. I declare public functions at the top of the class. Declaring an interface when there is only one class implementing it uselessly adds a file to maintain. Avoid it.
Nobody agrees about the use of interfaces over super/abstract classes ;)
The main reason to use interfaces and super/abstract classes is to enable polymorphism. In your case for instance, you have stuff moving on the screen (the player and the zombies and so on). Why not make them all move on the screen using the same method? Maybe inherit everything that's going to move on the screen from an object called "Movable" or something like that.
And if you're really into this stuff you might want to look at mixins as well. It's not something that Java supports directly but there are libraries built for it.
I have different kinds of zombies, but they all have the same attributes (x, y, health,
attack etc) so i wrote an interface Zombie which i implement by WalkingZombie,
RunningZombie TeleportingZombie etc. Is this the best thing to do? Am i better of with an
abstract class? Or with a super class?
an abstract class will be a super class for your zombies. an interface would also in some sense be a super class (super interface?) for your zombies.
the common properties suggest at least an abstract base class for common properties.
(I am not planning to partially implement functions - therefor my choice for an interface
instead of an abstract class)
not sure what you mean by this.
if you had different kinds of monsters (goblins, orcs, etc.) you might find behaviour common to these that would want to belong to different base classes. this would suggest an interface.
i would start with an abstract base class and see what the code tells you as you write it.
I have one class describing the main character (Survivor) and since it is pretty big i
wanted to write an interface with the different functions, so that i can easily see and
share the structure of it. Is it good practice? Or is it simply a waste of space and
time?
your survivor is what is called a player-character (as opposed to a non-player character - someone in a game who will normally not attack your survivor).
most games treat all of these character types as some kind of monster since they will all have many properties in common (health. magic, treasures, weapons, etc.)
so perhaps that's more of an argument for an interface.
see:
Using inheritance and polymorphism to solve a common game problem
Class diagram examples for RPG (Role Playing Game)
designing class hierarchy for typical characters in role playing game
I don't think that in your case your interface and class structure aligns well with the reality. In fact, I believe (correct me if I'm wrong) that each zombie can be walking, running, teleporting etc. depending on where it is.
Therefore, you should have a zombie class or interface and have actions which modify the zombie's state. The action would probably be an interface or an abstract class, so that you can apply any action to a zombie without knowing what the exact action does (e.g. action.perform(zobie)).
If you have different kinds of zombies, such as three-legged-zombie and one-armed zombies, you might want to implement different classes which handle the zombie stuff, such as displaying themselfes or validating state changes (e.g. a special kind of zombie may not accept to be teleported).
in terms of your Zombie example, the interface will do well, unless you have common code that you want all zombies to do.
Say you have a Move method, that makes walkingzombies walk, runningzombies run, etc. However, if you want "Move" to make any kind of zombie do something common, then the interface is going to force you to duplicate code, as you cant put a body in an interface.
My opinion is you better use abstract class called Creature as a super class for all type of, well, creatures, and extend it to Zombie for all type of zombies.
And you will also need an interface.. to define what are the things that a creature can do..
like maybe, walk, or claw, or scream...
the reason why you need an abstract class is to disable the instantiation of Creature, you wouldn't want to have a creature without knowing what creature it is, right?

Why are interfaces preferred to abstract classes?

I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?"
I tried giving a few answers like:
We can get only one Extends functionality
they are 100% Abstract
Implementation is not hard-coded
They asked me take any of the JDBC api that you use. "Why are they Interfaces?".
Can I get a better answer for this?
That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
Give them the answer they want.
Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well.
Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note.
First, highlight the positive things about interfaces, this is a MUST.
Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.
In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:
interface
abstract class
concrete class 1
concrete class 2
The interface is there for a couple of reasons:
an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)
This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.
The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).
You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface.
You only get one shot at inheritance. If you make an abstract class rather than an interface, someone who inherits your class can't also inherit a different abstract class.
You can implement more than one interface, but you can only inherit from a single class
Abstract Classes
1.Cannot be instantiated independently from their derived classes. Abstract class constructors are called only by their derived classes.
2.Define abstract member signatures that base classes must implement.
3.Are more extensible than interfaces, without breaking any version compatibility. With abstract classes, it is possible to add additional nonabstract members that all derived classes can inherit.
4.Can include data stored in fields.
5.Allow for (virtual) members that have implementation and, therefore, provide a default implementation of a member to the deriving class.
6.Deriving from an abstract class uses up a subclass's one and only base class option.
Interface
1.Cannot be instantiated.
2.Implementation of all members of the interface occurs in the base class. It is not possible to implement only some members within the implementing class.
3.Extending interfaces with additional members breaks the version compatibility.
4.Cannot store any data. Fields can be specified only on the deriving classes. The workaround for this is to define properties, but without implementation.
5.All members are automatically virtual and cannot include any implementation.
6.Although no default implementation can appear, classes implementing interfaces can continue to derive from one another.
As devinb and others mention, it sounds like the interviewer shows their ignorance in not accepting your valid answers.
However, the mention of JDBC might be a hint. In that case, perhaps they are asking for the benefits of a client coding against an interface instead of a class.
So instead of perfectly valid answers such as "you only get one use of inheritance", which are relating to class design, they may be looking for an answer more like "decouples a client from a specific implementation".
Abstract classes have a number of potential pitfalls. For example, if you override a method, the super() method is not called unless you explicitly call it. This can cause problems for poorly-implemented overriding classes. Also, there are potential problems with equals() when you use inheritance.
Using interfaces can encourage use of composition when you want to share an implementation. Composition is very often a better way to reuse others objects, as it is less brittle. Inheritance is easily overused or used for the wrong purposes.
Defining an interface is a very safe way to define how an object is supposed to act, without risking the brittleness that can come with extending another class, abstract or not.
Also, as you mention, you can only extend one class at a time, but you can implement as many interfaces as you wish.
Abstract classes are used when you inherit implementation, interfaces are used when you inherit specification. The JDBC standards state that "A connection must do this". That's specification.
When you use abstract classes you create a coupling between the subclass and the base class. This coupling can sometimes make code really hard to change, especially as the number of subclasses increases. Interfaces do not have this problem.
You also only have one inheritance, so you should make sure you use it for the proper reasons.
"Why Interfaces are preferred over
Abstract classes?"
The other posts have done a great job of looking at the differences between interfaces and abstract classes, so I won't duplicate those thoughts.
But looking at the interview question, the better question is really "When should interfaces be preferred over abstract classes?" (and vice versa).
As with most programming constructs, they're available for a reason and absolute statements like the one in the interview question tend to miss that. It sort of reminds me of all the statement you used to read regarding the goto statement in C. "You should never use goto - it reveals poor coding skills." However, goto always had its appropriate uses.
Respectfully disagree with most of the above posters (sorry! mod me down if you want :-) )
First, the "only one super class" answer is lame. Anyone who gave me that answer in an interview would be quickly countered with "C++ existed before Java and C++ had multiple super classes. Why do you think James Gosling only allowed one superclass for Java?"
Understand the philosophy behind your answer otherwise you are toast (at least if I interview you.)
Second, interfaces have multiple advantages over abstract classes, especially when designing interfaces. The biggest one is not having a particular class structure imposed on the caller of a method. There is nothing worse than trying to use a method call that demands a particular class structure. It is painful and awkward. Using an interface anything can be passed to the method with a minimum of expectations.
Example:
public void foo(Hashtable bar);
vs.
public void foo(Map bar);
For the former, the caller will always be taking their existing data structure and slamming it into a new Hashtable.
Third, interfaces allow public methods in the concrete class implementers to be "private". If the method is not declared in the interface then the method cannot be used (or misused) by classes that have no business using the method. Which brings me to point 4....
Fourth, Interfaces represent a minimal contract between the implementing class and the caller. This minimal contract specifies exactly how the concrete implementer expects to be used and no more. The calling class is not allowed to use any other method not specified by the "contract" of the interface. The interface name in use also flavors the developer's expectation of how they should be using the object. If a developer is passed a
public interface FragmentVisitor {
public void visit(Node node);
}
The developer knows that the only method they can call is the visit method. They don't get distracted by the bright shiny methods in the concrete class that they shouldn't mess with.
Lastly, abstract classes have many methods that are really only present for the subclasses to be using. So abstract classes tend to look a little like a mess to the outside developer, there is no guidance on which methods are intended to be used by outside code.
Yes of course some such methods can be made protected. However, sadly protected methods are also visible to other classes in the same package. And if an abstract class' method implements an interface the method must be public.
However using interfaces all this innards that are hanging out when looking at the abstract super class or the concrete class are safely tucked away.
Yes I know that of course the developer may use some "special" knowledge to cast an object to another broader interface or the concrete class itself. But such a cast violates the expected contract, and the developer should be slapped with a salmon.
If they think that X is better than Y I wouldn't be worried about getting the job, I wouldn't like working for someone who forced me to one design over another because they were told interfaces are the best. Both are good depending on the situation, otherwise why did the language choose to add abstract classes? Surely, the language designers are smarter than me.
This is the issue of "Multiple Inheritance".
We can "extends" not more than one abstarct class at one time through another class but in Interfaces, we can "implement" multiple interfaces in single class.
So, though Java doesn't provide multiple inheritance in general but by using interfaces we can incorporate multiplt inheritance property in it.
Hope this helps!!!
interfaces are a cleaner way of writing a purely abstract class. You can tell that implementation has not sneaked in (of course you might want to do that at certain maintenance stages, which makes interfaces bad). That's about it. There is almost no difference discernible to client code.
JDBC is a really bad example. Ask anyone who has tried to implement the interfaces and maintain the code between JDK releases. JAX-WS is even worse, adding methods in update releases.
There are technical differences, such as the ability to multiply "inherit" interface. That tends to be the result of confused design. In rare cases it might be useful to have an implementation hierarchy that is different from the interface hierarchy.
On the downside for interfaces, the compiler is unable to pick up on some impossible casts/instanceofs.
There is one reason not mentioned by the above.
You can decorate any interface easily with java.lang.reflect.Proxy allowing you to add custom code at runtime to any method in the given interface. It is very powerful.
See http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html for a tutorial.
interface is not substitute for abstract class.
Prefer
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Refer to this related SE question for use cases of both interface and abstract class
Interface vs Abstract Class (general OO)
Use case:
If you have to use Template_method pattern, you can't achieve with interface. Abstract class should be chosen to achieve it.
If you have to implement a capability for many unrleated objects, abstract class does not serve the purpose and you have to chose interface.
You can implement multiple interfaces, but particularly with c# you can not have multiple inheritances
Because interfaces are not forcing you into some inheritance hierarchy.
You define interfaces when you only require that some object implement certain methods but you don't care about its pedigree. So someone can extend an existing class to implement an interface, without affecting the previously existing behavior of that class.
That's why JDBC is all interfaces; you don't really care what classes are used in a JDBC implementation, you only need any JDBC implementation to have the same expected behavior. Internally, the Oracle JDBC driver may be very different from the PostgreSQL driver, but that's irrelevant to you. One may have to inherit from some internal classes that the database developers already had, while another one may be completely developed from scratch, but that's not important to you as long as they both implement the same interfaces so that you can communicate with one or the other without knowing the internal workings of either.
Well, I'd suggest the question itself should be rephrased. Interfaces are mainly contracts that a class acquires, the implementation of that contract itself will vary. An abstract class will usually contain some default logic and its child classes will add some more logic.
I'd say that the answer to the questions relies on the diamond problem. Java prevents multiple inheritance to avoid it. ( http://en.wikipedia.org/wiki/Diamond_problem ).
They asked me take any of the JDBC api
that you use. "Why are they
Interfaces?".
My answer to this specific question is :
SUN doesnt know how to implement them or what to put in the implementation. Its up to the service providers/db vendors to put their logic into the implementation.
The JDBC design has relationship with the Bridge pattern, which says "Decouple an abstraction from its implementation so that the two can vary independently".
That means JDBC api's interfaces hierarchy can be evolved irrespective of the implementation hierarchy that a jdbc vendor provides or uses.
Abstract classes offer a way to define a template of behavior, where the user plugins in the details.
One good example is Java 6's SwingWorker. It defines a framework to do something in the background, requiring the user to define doInBackground() for the actual task.
I extended this class such that it automatically created a popup progress bar. I overrode done(), to control disposal of this pop-up, but then provided a new override point, allowing the user to optionally define what happens after the progress bar disappears.
public abstract class ProgressiveSwingWorker<T, V> extends SwingWorker<T, V> {
private JFrame progress;
public ProgressiveSwingWorker(final String title, final String label) {
SwingUtilities.invokeLater(new Runnable() {
#SuppressWarnings("serial")
#Override
public void run() {
progress = new JFrame() {{
setLayout(new MigLayout("","[grow]"));
setTitle(title);
add(new JLabel(label));
JProgressBar bar = new JProgressBar();
bar.setIndeterminate(true);
add(bar);
pack();
setLocationRelativeTo(null);
setVisible(true);
}};
}
});
}
/**
* This method has been marked final to secure disposing of the progress dialog. Any behavior
* intended for this should be put in afterProgressBarDisposed.
*/
#Override
protected final void done() {
progress.dispose();
try {
afterProgressBarDisposed(get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
protected void afterProgressBarDisposed(T results) {
}
}
The user still has the requirement of providing the implementation of doInBackground(). However, they can also have follow-up behavior, such as opening another window, displaying a JOptionPane with results, or simply do nothing.
To use it:
new ProgressiveSwingWorker<DataResultType, Object>("Editing some data", "Editing " + data.getSource()) {
#Override
protected DataResultType doInBackground() throws Exception {
return retrieve(data.getSource());
}
#Override
protected void afterProgressBarDisposed(DataResultType results) {
new DataEditor(results);
}
}.execute();
This shows how an abstract class can nicely provide a templated operation, orthogonal to the concept of interfaces defining an API contract.
Its depend on your requirement and power of implementation, which is much important.
You have got so many answer regarding this question.
What i think about this question is that abstract class is the evolution if API.
You can define your future function definition in abstract class but you don't need all function implementation in your main class but with interface you cant do this thing.

Categories