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.
Why are abstract or interface classes created, or when should we use abstract or interface classes?
Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.
If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
--EDIT - forgot to mention, Earwicker reminded me
Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that in mind before choosing.
The key difference is that you can implement multiple interfaces in a class, but only extend a single abstract class. This is because an abstract class can also define fields that store data, whereas an interface cannot.
An abstract class is a class, that has atleast one abstract method or you can also make all your methods as abstract. Obviously it cannot be instantiated. You have to inherit from an abstract class and implement the abstract methods in the inheriting class (i.e, the class extending the abstract class).
Interfaces are not classes at all (so don't call them interface class). Interfaces define the signature of methods without any implementation. Also interfaces have no member-fields. If you implement an interface in a class, you have to provide implementations for all the methods provided by the interface.
It makes sense to define a generalized API for some stuff, that can have completely different implementations. Abstract classes are more useful for classes that do mainly the same, but have some subtle differences. You can combine both approaches.
A good example is the collections framework of the Java class-library. You have the interface List, that defines how Lists have to behave. Some implementations are for instance ArrayList and LinkedList. As they behave similar, the stuff that works the same for both is implemented in the abstract class AbstactList, both inherit this.
See Interface is basically a "Contract". When you are defining an interface you are defining a Contract. Where abstract classes are extended, interfaces are Implemented.
Let's consider an example.
public interface Friend {
void hello();
}
Now you have defined a contract which says that any class which wants to implement Friend needs to provide a definition for method hello().
Here is an implementation:
public class myFriend implements Friend {
public void hello()
println("Done");
}
Now myFriend has fulfilled the contract. Now the question is: Where should interfaces be used?
Interfaces help you define a behavior which must be implemented. Say you have a class A which defines some functionality. You want the other classes to use this class functionality only if they define particular behavior (methods). You enforce this restriction in term of interface.
SamuelCarrijo seems to have answered this question well.
In addition for Java, some frameworks require an interface to work with. I'm thinking of (say) dynamic proxies, or some client/server proxying frameworks. This is because they use introspection on the object to determine methods implemented by the interfaces implemented by the object. So occasionally you have to implement an interface for an object where, perhaps, you wouldn't normally bother.
Note this reason for interfaces is specific to Java.
Abstract classes are used when you are building an inheritance hierarchy. However, most inheritance hierarchies should not be too "deep" (i.e. too many levels of inheritance). Many object oriented design books will favor interfaces over inheritance (one book I read once quoted a developer as saying that "inheritance is the single coolest [object oriented] feature you won't implement"), as this allows classes to be assigned behaviors "by contract", where the contract is the interface.
It is worth noting samuelcarrijo's answer - if you want to have a default implementation of a method, you would have to use an abstract class that has a concrete implementation of the method to give it a default implementation. This default implementation can be overridden in child classes.
Hope this helps!
Related
This question already has answers here:
Why an interface can not implement another interface?
(7 answers)
Closed 9 years ago.
EDIT: The simple answer to my question is that Java allows one interface to extend multiple other interfaces. This is what answers my logical question of how you group interfaces together in a common interface. This answer did not appear in the dupe question. Also the question was different, it was not about creating interface groups.
Is there a reason in Java you cannot define one interface as implementing other interfaces? The answer I've seen and been dissatisfied with is that "interfaces themselves don't contain implementation, so how could an interface implement other other interfaces?" Well, that's a weak answer in my opinion, because its more a nod to English semantics than it is logical interpretation of the scenario. The logical interpretation of the scenario is since we can define classes to implement many interfaces, why can't we define an interface that itself represents a collection of interfaces.
Suppose you have many classes that you want to each implement a large, common set of many interfaces. As it currently stands, you'd have to explicitly write out the list for each class. This means that if later you had to add another interface to your list of many, you'd have to modify each class. Having all the interfaces consolidated in one "super interface" would allow the programmer to make the change in only one place.
And before you answer "make an abstract superclass that implements the list of interfaces, and have all your subclasses extend that superclass", keep in mind you cannot assume these classes do not already extend classes. One of the whole benefits of the implements keyword is so that you can adapt a class without having to change its taxonomy, right?
I guess the long story short is: Why can't programmers define interfaces that are just groups of other interfaces? Or, maybe the better question is: If I can't define an interface as implementing other interfaces, HOW can I define interfaces that are groups of other interfaces?
For those of you that prefer code, what I'm asking is why instead of doing this...
public class Foo extends ParentClass1 implements IBar1, IBar2, IBar3{
}
public class Baz extends ParentClass2 implements IBar1, IBar2, IBar3{
}
...wouldn't it make more sense for Java to allow this:
public interface IAllBar implements IBar1, IBar2, IBar3{
}
public class Foo extends ParentClass1 implements IAllBar{
}
public class Baz extends ParentClass2 implements IAllBar{
}
That way, later, if I create IBar4 I only have to modify IAllBar.java instead of Foo.java AND Baz.java.
Edit: So according to below answers I can define IAllBar to EXTEND all those interfaces and I'll get exactly what I want. I'm glad some people are willing to read an entire post before jumping to the bottom to post mean responses.
You can define an interface that's a collection of other interfaces. Its called extending an interface. You can extend multiple interfaces.
As for why you can't define methods in an interface, it's how Java interfaces were defined. And the problem you speak of are the consequences of single inheritance.
However you will be pleased to know that in the new upcoming Java 8 there's an feature called Virtual Extension Methods which addresses the large code base problems you speak of.
Personally I think it's useful in legacy code bases for quick refactoring, but if the system is well designed you should be able to get rid of the default implementations later. And overusing this feature will only result in all the disadvantages of multiple inheritance.
Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.
I believe what you should do is extend interfaces.
You could do this as shown below:
public interface ManBearPig implements Man, Bear, Pig {
//interface body
}
You could then implement ManBearPig where you need it.
The thing you need to keep in mind is that interfaces support multiple inheritance.
To understand this consider the idea that interfaces Man, Bear, and Pig might each have the method walk() included within them.
If you were to implement ManBearPig in a class and call the walk() method it would implement the walk method of Man, Bear, and pig simultaneously.
According to my understanding, your problem statement is:
How to design a Type hierarchy where a group of Classes implement same set of Interfaces and a number of behaviors exposed by the interfaces have common implementation.
This kind of design problem can be solved in Java in the following way (explaining by your example code)
public abstract class AbstractAllBar implements IBar1, IBar2, IBar3{
/* Provide implementations of methods whose behavior remains unchanges for all of it's children classes.*/
}
Now this abstract class can be extended by the classes who have common set of behaviors as defined by the abstract class AbstractAllBar.
public class ParentClass1 extends AbstractAllBar {
.......
}
public class ParentClass2 extends AbstractAllBar {
.......
}
public class Foo extends ParentClass1 {
}
public class Baz extends ParentClass2 {
}
This kind of abstract classes provide Skeleton Implementation. Examples of Skeleton Implementation can be found in Collection API. You can refer source code of AbstractList and AbstractSet to make it more clear.
This question already has answers here:
Abstract class vs Interface in Java
(15 answers)
Closed 9 years ago.
In abstract class we can make all methods abstract so that it can work like an interface, so why to use interface at all?? One of the reason I could come up was that we can implement multiple interface not extend multiple class.. Is there any design or performance related thing involved??
You already got the answer. Using Interfaces we can enforce multiple types of behaviours where as using classes will not work for you. For example, you can enforce a class to be IComparable as well as INumerable however it is not possible if you want to do it with classes.
You've already identified the one thing that interfaces allow that abstract classes don't allow. One class can't extend multiple abstract classes.
Is there any design or performance related thing involved??
There is no performance difference.
You could argue that the single inheritance restriction of abstract classes (in fact, all classes) makes this "a design thing" though. Certainly it would seriously restrict your use of polymorphism in an OO design.
(You could also argue that you can't follow the maxim of "programming to the interface" when you don't have interfaces. However, that is a weak argument ... a terminological quibble.)
Design wise it is preferred guidelines to use Interface for you code behavior/contract/functionality definition (see List interface) and use Abstract class where you have atlease some reusable (via inheritance) method implementation .
Though having all abstract method is possible, but in such cases an Interface is preferred.
Trying to understand a question I got wrong on a test:
How does inheritance differ from implementing interfaces?
With inheritance, a class gains behavior from its superclass.
With interfaces, a class gains behavior from the interface it implements. (this is the one I chose)
With inheritance, a class must implement the methods defined by its superclass.
With interfaces, a class gains both instance variables and behaviors from the interface it implements.
The way I was thinking is that interfaces define behavior, while superclasses define characteristics... or are they the same? Or am I completely backwards in my understanding?
Edit: I guess I should specify that I do know the difference between interfaces and inheritance. I'm just wondering about the two options which use the term behavior. I don't know if the prof was nitpicking about terminology, or if he asked the question poorly.
I know that when you implement an interface, you have to implement all the methods as defined in the interface. As such, I would say that the interface defines the behavior that a class must have, but extending another superclass (although it does also define some behaviors (more can be given to the subclass), it doesn't seem to fit as strongly as the interface defining behaviors. If the class implements an interface, you can be sure that it has certain behaviors.
Maybe the question was meant to ask whether or not the interface itself has the code for the behavior, or if it's just the definition - which if worded that way, I would have known the answer.
I think some of your misunderstanding might stem purely from semantics. Perhaps a more straightforward way of describing an interface is that it defines an API but does not provide an implementation of that API. One caveat is that I will use Java for my example but in a language like C++, implementing an interface is inheritance of a special sort - namely inheriting from a class consisting of pure virtual functions.
In Java, for instance, you might have an EventListener interface defined as:
public interface IEventListener {
public void handleEvent(Event event);
}
The interface does not, to use the question's verbiage, say anything about how a class that implements the IEventListener interface will behave when it receives an event it only ensures that any class implementing this interface will have the characteristic of being able to receive an event of type Event.
Inheritance, on the other hand, allows super classes to also inherit behavior (implementation). For instance, consider the following Java base class:
public abstract BaseClass {
public void baseMethod(int value) {
System.out.println(int);
}
public class SubClass extends BaseClass {
}
Any class that inherits from BaseClass gains both the API (characteristics) of BaseClass and also the implementation (behavior). In other words not only can you invoke instanceOfSubClass.baseMethod(1), a characteristic, doing so will result in the behavior defined in the BaseClass, namely 1 being printed to the console.
So your answer (2) is incorrect because interfaces do not specify behavior (implementation) only API (characteristics). Inheritance can handle both.
I think the point of the question is to explain that inheritance is specifically useful when you want to share behavior and not just API. That said, implementation (behavior) can also be shared via composition and such a strategy is often better - see Item 16 in Bloch's Effective Java for an excellent discussion.
When you implement an Interface, you don't necessarily care much for the implementation. Also remember that you can implement as many interfaces as you want, since they only specify contracts but not how to fulfill them. The creator of the interface lets you take care of that.
When you extend an Object it's usually because you need some functionality which an already existing object already got the majority of, but will only need that bit extra. Or you want to redefine some of the existing behaviour of an already existing object.
To give you the answer: 1 is right. You don't HAVE to implement the methods of a superclass (Inheritance). Only when it's abstract the next subclass of this superclass needs to implement the methods (like in an interface).
An object implementing an x Interface tells the object that it must do all actions (methods) listed in the definition of an interface. So in the object that implements x, you need to implements all actions. An interface cannot be instanciated.
But when you inherit from an object y, the object y may already have an implementation of some actions. if not the method will be marked as abstract (in java) and you need to implement it in your inherited object.
This is a very common OO design question in Java.
Sincerely recommend this very good article on this topic that explains it well:
http://www.javaworld.com/javaqa/2001-04/03-qa-0420-abstract.html
The correct answer is 1. The answer you chose (option 2) is wrong because interfaces technically do not have any behavior. They are just a list of abstract methods. You can consider them more as a template on which you can base your classes. For example, suppose a project is split into two parts, which need to be integrated at the end. Each team could use a common interface to base their classes on, so that integration would be a much easier job.
with inheritance, you get a cat. with an interface, you get the skeleton of a cat.
You gain behavior and implementation from inheritance. Remember that a subclass inherits all non-constructor and private methods from it's superclass. This means that you may inherit functionality (implementation) of certain methods.
With implementation you gain just behavior. All you are doing with implementation is signing a contract with the compiler, saying that you promise to override all abstract methods defined in the implemented class or interface.
I hope this helped.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Abstract class and Interface class?
When i need to use abstract class and interface in Java?
My doubt is
Which situation i need to use abstract class and which situation i need to use interface.
interface satisfy the abstract class properties. so then why we need especially abstract class?
i know, that abstract class contains abstract methods and non abstract methods, but we can use abstract class as a ordinary class, then the result will be same in the both classes. the ordinary class also inherited same as abstract class. So why we need abstract class.
If anybody know the good example please reply me.
Thanks.
Another important aspect of abstract class is that unlike interface, adding new methods to it won't break binary compatibility. So, from the API evolution point of view, especially when you can expect additions to the public API, abstract classes are more preferable.
I would say that there are two types of inheritance. One I would say as Implementation Inheritance and other as Contract Inheritance.
Abstract classes are used for having Implementation Inheritance. You can extend/change the behavior of your super/parent class.
Interfaces would go for Contract Inheritance. Where you are more interested in having the class implement some kind of a contract (service methods with arguments - more of a contract) and the behavior is different for different implementation, nothing generic that you can bundle up in an abstract class and extend the behavior.
You need to use abstract classes if you want to apply the template pattern http://en.wikipedia.org/wiki/Template_method_pattern, usually in framework code. As a rule of thumb, if you're not intending to implement the template pattern, you're better off with interfaces, which permit loose coupling, the way spring framework does. Loose coupling leads to a design open to evolutions and a better testability, with techniques like mock objects (http://easymock.org)
This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
Can anyone tell me what exactly the difference between an completely abstract class and an interface?
An Abstract class can also have all its methods as abstract. An interface has all its methods as abstract. What is the main difference between the two in this scenario?
If there is difference between a pure abstract Class and interface? What is the use of interface? Where interface is being used we can make use of pure abstract class?
To complete the former answers :
An interface is a "contract". If a class implements an interface it have to propose all the services listed in the interface.
An abstract class is a skeleton. It defines a certain way its extended classes will work while letting them some free space (the abstract methods) to be unique.
A pure abstract class doing the same thing as a interface but have the problem of unique extending so, for me, it have no interest
Every interface is implicitly abstract: Every method declaration in the body of interface is implicitly abstract and public.
An abstract class has methods that can contain implementation. Abstract methods can be either public, protected or default access (package visible). Unlike interfaces abstract classes can contain fields that are not static and final.
Also see:
Interfaces vs Abstract classes and the
Java tutorial
In Java and C#, one can use multiple interfaces to derive from and only a single class to inherit from,
One reason to choose pure abstract over interface is to force sub classes to implement particular methods that are implemented by a super class.
For example (in Java),
Say you want all extending classes to implement toString(), equals(), and hashCode().
You could create an interface called ForceSomeMethods for that contract, but those methods are implicitly implemented by Object.
Making ForceSomeMethods a pure abstract class with toString(), etc as abstract methods, all subclasses will be forced to implement those methods.
It's not a very theorotical explaination but, programatically it's all correct
Interface Abstract Class
Extend Class No Yes
Extend Abstract Class No Yes
Implement Interface Yes(Extend Interface) Yes
Variables Public Static Final Public/Protected/Private/static/final/transient/volatile
Contain Non-Public Method No Public/Protected/*Private
Contain Abstract Method Yes Yes
Contain No-Body, Non-Abstract Method Yes No
Contain Defined Method No Yes
Contain Main Method No Yes
*Abstract classes can have private methods, but not abstract private methods.
An abstract class can provide an implementation, i.e. (public, protected, private) method bodies. An interface can just declare public method signatures. These methods have to be realized (in the form of method bodies) by classes implementing the interface.
There are three differences:
Interfaces can only declare public methods (i.e. no protected or package-private visible methods) and can not declare any fields
Subclasses can only extend at most one abstract class, but can implement any number of interfaces
The abstract class can also have implementations for some or all of the methods
I'm just going to address one point (mainly because the other questions have been addressed already):
"Where interface is being used we can
make use of pure abstract class?"
In theory, you could. However, you will lose flexibility and loose coupling to some extent. It's far more preferable to code to interfaces and pass those around, especially in Inversion of Control (IoC) scenarios and from an integration point of view, as this allows far greater extensibility.
Since the question is about pure abstract classes then I'd say the answer is going to be related to inheritance and scope. It's something I've wondered myself many times and this is what I've come up with.
Obviously the features related to multiple inheritance have been answered previously so I won't go in to any of that. Scope is a big one though.
In an interface you can't define a member's access modifiers since they are implicitly public,...you are defining the public interface for it's eventual implementation. There's an important difference there since you can define a protected abstract member in a pure abstract class.
Inheriting from such a class definition would force the inheritor to implement the abstract member but scope it privately to consumers of the class (though it would have to be defined as protected so unless the class was marked as sealed further inheritors would have access).
In essence you can define a private interface using pure abstract classes. Whether that's a good idea is a different question altogether but one good use I've seen it used for is to enforce design patterns and standardize class designs.
HTH
You can use Interface for multiple inheritance, but you can't use abstract class for multiple inheritance.
All the methods in Interface is public by default, by in abstract class, only the methods which you've set as an abstract need to be declared public.
A class can implement multiple interfaces, but only extend from one class (abstract or otherwise). If you need to specify an interface, then you should use an interface, so that classes may implement multiple of your interfaces.