As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Most OO languages prefix their interface names with a capital I, why does Java not do this? What was the rationale for not following this convention?
To demonstrate what I mean, if I wanted to have a User interface and a User implementation I'd have two choices in Java:
Class = User, Interface = UserInterface
Class = UserImpl, Interface = User
Where in most languages:
Class = User, Interface = IUser
Now, you might argue that you could always pick a most descriptive name for the user implementation and the problem goes away, but Java's pushing a POJO approach to things and most IOC containers use DynamicProxies extensively. These two things together mean that you'll have lots of interfaces with a single POJO implementation.
So, I guess my question boils down to: "Is it worth following the broader Interface naming convention especially in light of where Java Frameworks seem to be heading?"
I prefer not to use a prefix on interfaces:
The prefix hurts readability.
Using interfaces in clients is the standard best way to program, so interfaces names should be as short and pleasant as possible. Implementing classes should be uglier to discourage their use.
When changing from an abstract class to an interface a coding convention with prefix I implies renaming all the occurrences of the class --- not good!
Is there really a difference between:
class User implements IUser
and
class UserImpl implements User
if all we're talking about is naming conventions?
Personally I prefer NOT preceding the interface with I as I want to be coding to the interface and I consider that to be more important in terms of the naming convention. If you call the interface IUser then every consumer of that class needs to know its an IUser. If you call the class UserImpl then only the class and your DI container know about the Impl part and the consumers just know they're working with a User.
Then again, the times I've been forced to use Impl because a better name doesn't present itself have been few and far between because the implementation gets named according to the implementation because that's where it's important, e.g.
class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO
There may be several reasons Java does not generally use the IUser convention.
Part of the Object-Oriented approach is that you should not have to know whether the client is using an interface or an implementation class. So, even List is an interface and String is an actual class, a method might be passed both of them - it doesn't make sense to visually distinguish the interfaces.
In general, we will actually prefer the use of interfaces in client code (prefer List to ArrayList, for instance). So it doesn't make sense to make the interfaces stand out as exceptions.
The Java naming convention prefers longer names with actual meanings to Hungarian-style prefixes. So that code will be as readable as possible: a List represents a list, and a User represents a user - not an IUser.
There is also another convention, used by many open source projects including Spring.
interface User {
}
class DefaultUser implements User {
}
class AnotherClassOfUser implements User {
}
I personally do not like the "I" prefix for the simple reason that its an optional convention. So if I adopt this does IIOPConnection mean an interface for IOPConnection? What if the class does not have the "I" prefix, do I then know its not an interface..the answer here is no, because conventions are not always followed, and policing them will create more work that the convention itself saves.
As another poster said, it's typically preferable to have interfaces define capabilities not types. I would tend not to "implement" something like a "User," and this is why "IUser" often isn't really necessary in the way described here. I often see classes as nouns and interfaces as adjectives:
class Number implements Comparable{...}
class MyThread implements Runnable{...}
class SessionData implements Serializable{....}
Sometimes an Adjective doesn't make sense, but I'd still generally be using interfaces to model behavior, actions, capabilities, properties, etc,... not types.
Also, If you were really only going to make one User and call it User then what's the point of also having an IUser interface? And if you are going to have a few different types of users that need to implement a common interface, what does appending an "I" to the interface save you in choosing names of the implementations?
I think a more realistic example would be that some types of users need to be able to login to a particular API. We could define a Login interface, and then have a "User" parent class with SuperUser, DefaultUser, AdminUser, AdministrativeContact, etc suclasses, some of which will or won't implement the Login (Loginable?) interface as necessary.
Bob Lee said once in a presentation:
whats the point of an interface if you
have only one implementation.
so, you start off with one implementation i.e. without an interface.
later on you decide, well, there is a need for an interface here, so you convert your class to an interface.
then it becomes obvious: your original class was called User. your interface is now called User. maybe you have a UserProdImpl and a UserTestImpl. if you designed your application well, every class (except the ones that instantiate User) will be unchanged and will not notice that suddenly they get passed an interface.
so it gets clear -> Interface User implementation UserImpl.
In C# it is
public class AdminForumUser : UserBase, IUser
Java would say
public class AdminForumUser extends User implements ForumUserInterface
Because of that, I don't think conventions are nearly as important in java for interfaces, since there is an explicit difference between inheritance and interface implementation. I would say just choose any naming convention you would like, as long as you are consistant and use something to show people that these are interfaces. Haven't done java in a few years, but all interfaces would just be in their own directory, and that was the convention. Never really had any issues with it.
In my experience, the "I" convention applies to interfaces that are intended to provide a contract to a class, particularly when the interface itself is not an abstract notion of the class.
For example, in your case, I'd only expect to see IUser if the only user you ever intend to have is User. If you plan to have different types of users - NoviceUser, ExpertUser, etc. - I would expect to see a User interface (and, perhaps, an AbstractUser class that implements some common functionality, like get/setName()).
I would also expect interfaces that define capabilities - Comparable, Iterable, etc. - to be named like that, and not like IComparable or IIterable.
Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:
public void doSomething(Collection someStuff) {
...
}
than this:
public void doSomething(Vector someStuff) {
...
}
If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.
The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.
If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.
=v= The "I" prefix is also used in the Wicket framework, where I got used to it quickly. In general, I welcome any convention that shortens cumbersome Java classnames. It is a hassle, though, that everything is alphabetized under "I" in the directories and in the Javadoc.
Wicket coding practice is similar to Swing, in that many control/widget instances are constructed as anonymous inner classes with inline method declarations. Annoyingly, it differs 180° from Swing in that Swing uses a prefix ("J") for the implementing classes.
The "Impl" suffix is a mangly abbreviation and doesn't internationalize well. If only we'd at least gone with "Imp" it would be cuter (and shorter). "Impl" is used for IOC, especially Spring, so we're sort of stuck with it for now. It gets a bit schizo following 3 different conventions in three different parts of one codebase, though.
Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?
If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.
Related
This question already has answers here:
Interface naming in Java [closed]
(11 answers)
Closed 9 years ago.
what is the convention to name interface and its implementation class in java?
Interface : ISomeService
Impl : SomeService
or
Interface : SomeService
Impl : SomeServiceImpl
Thanks!
Name your Interface what it is. Truck. Not ITruck because it isn't an ITruck it is a Truck. An Interface in Java is a Type. Then you have DumpTruck, TransferTruck, WreckerTruck, CementTruck, etc. When you are using the Interface Truck in place of a sub-class you just cast it to Truck. As in List<Truck>. Putting I in front is just crappy hungarian style notation tautology that adds nothing but more stuff to type to your code.
All modern Java IDE's mark Interfaces and Implementations and what not without this silly notation. Don't call it TruckClass that is tautology just as bad as the IInterface tautology.
If it is an implementation it is a class. The only real exception to this rule, and there are always exceptions is AbstractTruck. Since only the sub-classes will every see this and you should never cast to an Abstract class it does add some information that the class is abstract and to how it should be used. You could still come up with a better name than AbstractTruck and use BaseTruck instead. But since Abstract classes should never be part of any public facing interface it is an acceptable exception to the rule.
And the Impl suffix is just more noise as well. More tautology. Anything that isn't an interface is an implementation, even abstract classes which are partial implementations. Are you going to put that silly Impl suffix on every name of every Class?
The Interface is a contract on what the public methods and properties have to support, it is also Type information as well. Everything that implements Truck is a Type of Truck.
Look to the Java standard library itself. Do you see IList, ArrayListImpl, LinkedListImpl? No you see. List and ArrayList and LinkedList. Here is a nice article about this exact question. Any of these silly prefix/suffix naming conventions all violate the DRY principal as well.
Also if you find yourself adding DTO, JDO, BEAN or other silly repetitive suffixes to objects then they probably belong in a package instead of all those suffixes. Properly packaged namespaces are self documenting and reduce all the useless redundant information in these really poorly conceived proprietary naming schemes that most places don't even adhere to in a consistent manner. If all you can come up with to make your Class name unique is suffixing it with Impl, then you need to rethink having an Interface at all. So when you have an situation where you have an Interface and a single Implementation that is not uniquely specialized from the Interface you probably don't need the Interface.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I work on a Java web-app that uses Spring for dependency injection and JMock for mocking out these dependencies in our unit tests.
Currently our team is at a point were we have a few different opinions in terms of how to name certain interfaces that we use. We have no issue with naming the interfaces in our domain that have multiple implementations, that is simple. However, when it comes to interfaces for which we only have one implementation and intend on only having one implementation in the future, we have hit a snag.
The reason that we have such interfaces is purely for mocking, for example, we have services and repositories that we mock out in our unit tests and these services will be named "DocumentMappingService" or for repositories "EmployeeRepository". At the moment some of the guys just prefix the associated interface name with an "I", i.e. "IDocumentMappingService" and "IEmployeeRepository". Others name the interface as I have above and then append an "Impl" after the interface name for the implementing class.
The third "faction" feels that both of these options are poor. Looking at literature such as the well-known "Growing object-oriented software, guided by tests" would lead one to believe that both of the before-mentioned options are poor and that the interface name should clearly define the contract and the implementing classes name should clearly specify how that contract has been implemented. We have found this quite difficult to do in the case I have mentioned above though.
I was hoping that someone out there has had a similar issue before and has some suggestions ito which option is the best and why. Also, if you think that the "I" and "Impl" options are both poor, then please suggest a specific alternative convention.
There's no "one" correct answer here. Naming is quite subjective but what matters the most is that it should be consistent throughout the code base. I would just like to add (to #fge's answer) some more options for you:
Making the Interfaces more generic.
EmployeeRepository implements Repository
DocumentMappingService implements MappingService
Calling your single implementations "defaults".
DefaultEmployeeRepository implements EmployeeRepository
DefaultDocumentMappingService implements DocumentMappingService
Calling your base implementations (if, sometimes extended) as "support".
EmployeeRepositorySupport implements EmployeeRepository
DocumentMappingServiceSupport implements DocumentMappingService
I come across these naming conventions a lot when using the Spring Framework.
Edit : In response to user nyxz's comment about the -Base or Base- convention.
Like I said before, naming is subjective and there's nothing wrong with using the Base nomenclature as such. But, personally, I don't prefer using it. Here's why:
If your implementations would mostly be used directly, then the code instantiating the classes leaves an impression of breaking the OOP hierarchy. That perhaps a specific derived class should have been instantiated.
If your implementations would mostly be extended from, then the word Base becomes redundant in a way. You're extending from it so, of course, it's a base class. Duh!
The 2nd point mostly applies to peripheral classes in your project. Extension points that you provide when you're publishing a framework or library to be used and extended in other projects.
On the other hand, a good use case for using the Base terminology would be for classes internal to your framework that factor common functionality out of other peripheral classes. Since, these classes aren't supposed to be instantiated directly, they are marked abstract, which is in line with the 1st point.
Here's the Adapter hierarchy from the Android framework as an example:
Interface hierarchy.
public interface Adapter
public interface ListAdapter extends Adapter
public interface SpinnerAdapter extends Adapter
The abstract Base class that factors out the common behaviour and interface implementations.
public abstract class BaseAdapter implements ListAdapter, SpinnerAdapter
Peripheral classes that are mostly instantiated but sometimes extended by an Android application.
public class SimpleAdapter extends BaseAdapter implements Filterable
public class ArrayAdapter<T> extends BaseAdapter implements Filterable
An answer to such a question can only reflect the tastes of the person who answers... So these are my tastes:
I hate the initial I. It brings nothing of value to the picture. It reminds me of the Hungarian notation where float variables were to be suffixed with _f or the like. No.
The Impl suffix is good enough. But on the other hand, it sounds weird.
I'd suggest two alternate proposals for a given interface Foo:
create a single implementation but not with the Impl suffix; find a more "appealing" name. For instance, TheOnlyOneFoo;
create a factory with an appended s: Foos. Then, a Foo instance would be a Foos.newInstance(whatever, args).
I prefer the second solution, for two reasons:
it can hide the fact that the real implementation has an ugly name;
it can be extended easily when you realize one day that "no, after all, there is more than one implementation for that": just add another static factory method; and if the only existing method in existence sounds too generic, you can just mark it as #Deprecated.
It could even be used in a manner so that all Foo implementations are package local, or even private to the factory. But stack traces would look worse...
No real solution there ;)
edit: as for mocking:
I'd recommend mockito. Really. It is very easy to use, and very powerful.
If those are "one-implementation classes" you are dealing with, maybe there is a better alternative in the JDK itself? What is it that you want to do exactly? The JDK has hidden treasures...
And as a final note... Have you considered the builder pattern?
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 9 years ago.
Let's say we have two classes, Tiger and Aeroplane.
One thing in common for these two types is the Speed. I know that it would be illogical to create a superclass ClassWithSpeed and then derive subclasses Aeroplane and Tiger from it.
Instead, it is better to create an interface that contains the method speed() and then implement it in Aeroplane and Tiger. I get that. But, we can do the same thing without interfaces. We could define method speed() in Aeroplane and method speed() in Tiger.
The only (maybe very big) flaw it would be that we couldn't "reach" the objects of Tiger and Aeroplane through an interface reference.
I am beginner in Java and OOP, and I would be very grateful if someone explained to me the role of interfaces.
Cheers!
It's:
public int howFast(Airplane airplane) {
return airplane.speed();
}
public int howFast(Tiger tiger) {
return tiger.speed();
}
public int howFast(Rocket rocket) {
return rocket.speed();
}
public int howFast(ThingThatHasntBeenInventedYet thingx) {
// wait... what? HOW IS THIS POSSIBLE?!
return thingx.speed();
}
...
vs
public int howFast(Mover mover) {
return mover.speed();
}
Now, imagine having to go back and change all those howFast functions in the future.
Interface or no, each class will have to implement or inherit the speed() method. An interface lets you use those disparate classes more easily, because they've each promised to behave in a certain way. You'll call speed(), and they'll return an int, so you don't have to write separate methods for every possible class.
When you find you need to handle speed differently because of a breakthrough in relativistic physics, you only need to update the methods that call speed(). When your great-granddaughter writes a class for HyperIntelligentMonkeyFish, she doesn't have to disassemble your ancient binary and make changes so that your code can monitor and control her mutant army. She needs only declare that HyperIntelligentMonkeyFish implements Mover.
Interfaces allow Java, since it is statically typed, to work around multiple inheritance limitations to the degree felt worthwhile by the language designers.
In a dynamic language (like Python, Ruby, etc.) you can just call the speed method on any arbitrary object and discover at runtime if it is there or not.
Java, on the other hand, is statically typed, which means the compiler has to agree that the method will be there ahead of time. The only way to do that on classes that don't share common ancestry, and may only have Object in common, is an interface.
Since objects can implement an arbitrary number of interfaces, this means you get the goodness of multiple inheritance (a single object that can pose as multiple different objects for different methods) without the downside (of conflicting implementations in the two super classes).
With Java 8, the designers of the language concluded that interfaces without any implementation was overly restrictive (they didn't like my solution I guess ;-)), so they allow for a default implementation, thus expanding the multi-inheritance options of interfaces, while still trying to avoid the conflicting implementation problem via a complex set of precedence rules so that there is an unambiguous default implementation to execute.
I am trying to explain the advantage of interface with the following example-
suppose you have another class where you need to use the tiger or AeroPlane as parameter. So by using interface you can call using
someObject.someMethod(ClassWithSpeed)
but if you dont use interface you can use
someObject.someMethod(Tiger)
someObject.someMethod(AeroPlane)
Now what should you do? Your probable answer will be like, "I will use two overloaded method".
This is okay so far, But
Say you need to add more options (say car, cycle, rabbit, tortoise.... 100 others). So what will you do to make the change of your existing code?? you will need to change a lots of things..
The overall example above has only one purpose. That is to say
"we need interface to create a better, reusable and properly object oriented
design"
N.B.
if you are sure the program is too small and you will never need to change them then I think it is okay to implement without interface
Defining an interface allows you to define methods that work not only on Aeroplane and Tiger, but also other classes that share the same interface.
For example, say your interface is IObjectWithSpeed. Then you can define a method like this -- in a single class that operates on IObjectWithSpeed objects.
public double calculateSecondsToTravel( IObjectWithSpeed obj, double distance ) {
return distance / obj.getSpeed();
}
Interfaces allow us to satisfy the open/closed principle - open for extension, but closed for modification. The single implementation of the method above doesn't need to be modified as new classes are defined that implement IObjectWithSpeed.
I want go into much theoretical details but will try to explain using this example.
Consider JDBC API. It is API used to deal with database related options in the Java. Now, there are so many databases in the industry. How would one write drivers for that? Well, the quick and dirty approach may be write own implementation using our own classes and API.
But think from the programmer's perspective. Will they start learning DATABASE DRIVER's API while using different database? The answer is NO.
So what is the solution to the problem ? Just have a well defined API which anyone can extend for his own implementation.
In JDBC API, there are some Interfaces which are Connection, ResultSet, PreparedStatement, Statement etc. Now each database vendor will implement the interface and will write his own implementation for that. Result ? : Reduced effort from the developer and easy understandability.
Now, what this custom implementation might consisting of ? It's simple. They do what, take ResultSet interface for example and implement it and in whatever method the ResultSet is gettting returned, return THE CLASS THAT IMPLEMENTS ResultSet interface like this
ResultSet rs=new ResultSetImpl(); //this is what they are doing internally.
So interface are like contracts. They define what your class is able to do and they give your application flexibility. You can create your own APIs using interfaces properly.
Hope this helps you.
An interface is not simply a method signature.
It is a type that represents a contract. The contract is the thing, not the method signatures. When a class implements an interface, it is because there is a contract for a shared behavior that the class has an interest in implementing as a type. That contract is implemented via the specified members which are usually method bodies but may also include static final fields.
It may be true that a tiger and an aeroplane both could be expressed as a type with a common behavior implemented through speed() ... and if so, then the interface represents the contract for expressing that behavior.
Aside from being descriptive for those classes' functionality, methods of an interface could be used without any knowledge about the classes implementing it, even for classes that were not yet defined.
So for example, if you'd need a class Transport that computes say efficient routes, it could be given a class that implements ClassWithSpeed as a parameter and use its method speed() for computing what it needs. This way you could use it with our class Aeroplane, but also with any class we define later, say Boat. Java will take care that if you want to use a class as a parameter to Transport it will implement ClassWithSpeed, and that any class implementing ClassWithSpeed implements the method speed() so that it can be used.
The interface (as a language construct) is used by the compiler to prove that the method call is valid and allows you to have dependent classes interact with the implementing class while having the least possible knowledge about the implementing class.
This is a very wide question to give a simple answer. I can recommend a book Interface Oriented Design: With Patterns. It explains all power of interfaces. And why we should not avoid them.
Have you tried using composition instead?, if I want 2 dissimilar classes to inherit the same abilities I use a class which takes an object of the type its working with by using abstract classes and checking the instances. Interfaces are useful for forcing methods to be including in the class but don't require any implementation or for 2 teams of coders to work on different coding areas.
Class Tiger {
public MovingEntity mover;
public Tiger(){
mover.speed=30;
mover.directionX=-1;
mover.move(mover);
}
}
Class Plane {
public MovingEntity mover;
public Plane(){
mover.speed=500;
mover.directionX=-1;
mover.move(mover);
}
Abstract Class Moverable(){
private int xPos;
private int yPos;
private int directionX;
private int directionY;
private int speed;
Class MovingEntity extends Moverable {
public void move(Moverable m){
if(m instanceof Tiger){
xPos+=directionX*speed;
yPos+=directionY*speed;
}else if(m instanceof Plane){
xPos+=directionX*speed;
yPos+=directionY*speed;
}
}
On language level, the only use of interfaces is, like you mentioned, to be able to refer to different classes in a common way. On people level, however, the picture looks different: IMO Java is strong when used in big projects where the design and the implementation are done by separate people, often from separate companies. Now, instead of writing a specification on a Word document, the system architects can create a bunch of classes that implementers can then directly insert in their IDEs and start working on them.
In other words it is more convenient instead of declaring that "Class X implements methods Y and Z in order for it to be used for purpose A, just to say that "Class X implements interface A"
Because creating interface gives you Polymorphism, across all those classes i.e. Tiger and Aeroplane.
You can extend from an (abstract or concrete) class when the base class's functionality is going to be the core of your child class's functionality as well.
You use interfaces when you want to add an augmented functionality to your class in addition to its core functionality. So using interfaces would give you Polymorphism even when its not your class's core functionality (because you've entered a contract by implementing the interface). This is a huge advantage over creating a speed() method with each class.
I'm creating a mock class for a Lexer object, and I think I may need to do some refactoring. I have two options:
Create an interface Lexer, and rename the current Lexer to something like RealLexer. Have MockLexer implement Lexer, and method calls take anything of type Lexer. I dislike that my precious Lexer class is now renamed to something that has no meaning if you don't know that there's a mock class.
Create an interface LexerInterface (which I already dislike, since it has Interface in its name), but allowing myself to keep the current Lexer the way it is. MockLexer then implements LexerInterface. Another downside is that method calls take LexerInterface as params.
Both options smell bad to me, so I figured I'd let standards decide for me. Has anyone had experience with this?
I'd definitely vote for using Lexer as your interface name. How about adding some information about how or why your implementation does its thing as part of the name?
E.g.:
StringParsingLexer
TokenizingLexer
SingleThreadedLexer
{ThirdPartyLibraryName}DelegatingLexer
Also, do you really need to be explicitly constructing a MockLexer? Using a framework like Mockito can make your testing considerably easier and faster; You can get started as easily as:
Lexer mockLexer = Mockito.mock(Lexer.class);
Mockito.when(mockLexer.doFoo()).thenReturn("bar");
My recommendation, as I stated in the comments, is to use Lexer for your interface and DefaultLexer for the default implementation. This pattern is used quite frequently and as such is very understandable to anyone who will be maintaining your code. As for the mock object, it would also be understandable to name this something like MockLexer.
As an example of a naming convention that Java uses:
javax.swing.table.TableModel is an interface
javax.swing.table.AbstractTableModel is an abstract class implementing TableModel
javax.swing.table.DefaultTableModel is an implementation of AbstractTableModel.
There is however, no recommendation in the Java Codding Conventions outside of using capital letters, nouns, etc.
I usually use option 1 - interfaces called Lexer, with default implementations called either DefaultLexer or LexerImpl. I like this, because I think it lets you talk about the classes easily - if you have multiple implementations of Lexers, then their concrete names can describe the implementation type - eg NativeLexer or TreeBasedLexer or whatever. As a commenter mentioned, then your mock class (if you have one) can follow this pattern with a name like MockLexer.
However, with mocking libraries such as the excellent Mockito, you can mock concrete classes anyway - so you no longer need to use interfaces everywhere in order to test things easily. Here is the example they give in their documentation:
//You can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);
That said, I would still recommend using interfaces instead of tying method signatures to concrete classes, because then things that use Lexer do not need to be tied to the implementation - this can be a massive gain in maintainability (eg if you need to have multiple implementations later).
In my experience there are two standards.
"Tag" your interface. (ILexer, LexerInterface, etc)
Use the name for your interface and use a different name for the concrete implementation.
I know these are already the options you presented. The trouble is, not one of them is firmly the "standard."
I strongly prefer option 2). A class name for an object should tend to be a noun that fits within the context of an "is-a" sentence. It feels weird to say that an object "is-a" LexerInterface whereas it is natural to say that an object "is-a" DefaultLexer.
Since ultimately my class or interface name represents a type, I shy away from "meta" information in a class or interface name.
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.