We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.
In what cases should we be using extends?
extends is used for either extending a base class:
class ClassX extends ClassY {
...
}
or extending an interface:
interface InterfaceA extends InterfaceB {
...
}
Note that interfaces cannot implement other interfaces (most likely because they have no implementation).
Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo for interfaces in the .NET world) and instead uses the difference between extends and implements to signify the difference to the programmer:
class ClassA extends ClassB implements InterfaceC, InterfaceD {
...
}
Here you can clearly see that you're building upon an existing implementation in ClassB and also implement the methods from two interfaces.
Is a matter of uses. Interfaces can be used as a contract with your application and then base classes can be use to extend that interface, so it is loosely couple.
Take for example Injection Dependency pattern:
You first write a contract:
public interface IProductRepository
{
IList<T> GetAllProducts();
}
Then you extend your contract with a base class:
public abstract BaseProductRepository : IProductRepository
{
public IList<T> GetAllProducts()
{ //Implementation }
}
Now you have the option to extend base into two or more concrete classes:
public class InternetProductRepository extends BaseProductRepository;
public class StoreProductRepository extends BaseProductRepository;
I hope this small examples clears the differences between extend and Implement. sorry that I did not use java for the example but is all OO, so I think you will get the point.
Thanks for reading, Geo
I did not complete the code for injection dependency pattern but the idea is there, is also well documented on the net. Let me know if you have any questions.
Actually, you can extend an interface - in the case where you're defining another interface.
There are lots of quasi-religious arguments about this issue and I doubt there's a clear right answer, but for what it's worth here's my take on things. Use subclassing (i.e. extends), when your various classes provide the same sort of functionality, and have some implementation details in common. Use interface implementation, in order to signal that your classes provide some particular functionality (as specified by the interface).
Note that the two are not mutually exclusive; in fact if a superclass implements an interface, then any subclasses will also be considered to implement that interface.
In Java there is no multiple inheritance, so that a (sub)class can only have one parent class, and subclassing should be considered carefully so as to choose an appropriate parent if any at all; choosing a parent that reflects just a small amount of the class' abilities is likely to end in frustration later if there are other sensible parent classes. So for example, having an AbstractSQLExecutor with SQL Server and Oracle subclasses makes a lot of sense; but having a FileUtils parent class with some utility methods in, and then subclassing that all over the place in order to inherit that functionality, is a bad idea (in this case you should likely declare the helper methods static, or hold a reference to a FileUtils instance, instead).
Additionally, subclassing ties you to implementation details (of your parent) more than implementing an interface does. I'd say that in general it's better merely to implement the interface, at least initially, and only form class hierarchies of classes in the same or similar packages with a clear hierarchical structure.
Like you said. the implement java keyword is used to implement an interface where the extends is used to extend a class.
It depends what you would like to do. Typically you would use an interface when you want to force implementation (like a contract). Similar to an abstract class (but with an abstract class you can have non-abstract methods).
Remember in java you can only extend one class and implement zero to many interfaces for the implementing class. Unlike C# where you can extend multiple classes using :, and where C# only uses the : symbol for both interfaces and classes.
extends keyword is used for either extending a concrete/abstract class. By extending, u can either override methods of parent class / inherit them. A class can only extend class.
U can also say interface1 extends intenface2.
implements keyword is used for implementing interface. In this case u have to define all the methods indicated in interface. A class can only implement interface.
Related
I was asked a question, I wanted to get my answer reviewed here.
Q: In which scenario it is more appropriate to extend an abstract class rather than implementing the interface(s)?
A: If we are using template method design pattern.
Am I correct ?
I am sorry if I was not able to state the question clearly.
I know the basic difference between abstract class and interface.
1) use abstract class when the requirement is such that we need to implement the same functionality in every subclass for a specific operation (implement the method) and different functionality for some other operations (only method signatures)
2) use interface if you need to put the signature to be same (and implementation different) so that you can comply with interface implementation
3) we can extend max of one abstract class, but can implement more than one interface
Reiterating the question: Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Interface vs. Abstract class
Choosing between these two really depends on what you want to do, but luckily for us, Erich Gamma can help us a bit.
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code, so the only way to avoid this would be to create a whole new Interface, which might not always be a good thing.
Abstract classes should primarily be used for objects that are closely related. Interfaces are better at providing common functionality for unrelated classes.
When To Use Interfaces
An interface allows somebody to start from scratch to implement your interface or implement your interface in some other code whose original or primary purpose was quite different from your interface. To them, your interface is only incidental, something that have to add on to the their code to be able to use your package. The disadvantage is every method in the interface must be public. You might not want to expose everything.
When To Use Abstract classes
An abstract class, in contrast, provides more structure. It usually defines some default implementations and provides some tools useful for a full implementation. The catch is, code using it must use your class as the base. That may be highly inconvenient if the other programmers wanting to use your package have already developed their own class hierarchy independently. In Java, a class can inherit from only one base class.
When to Use Both
You can offer the best of both worlds, an interface and an abstract class. Implementors can ignore your abstract class if they choose. The only drawback of doing that is calling methods via their interface name is slightly slower than calling them via their abstract class name.
reiterating the question: there is any other scenario besides these
mentioned above where specifically we require to use abstract class
(one is see is template method design pattern is conceptually based on
this only)
Yes, if you use JAXB. It does not like interfaces. You should either use abstract classes or work around this limitation with generics.
From a personal blog post:
Interface:
A class can implement multiple interfaces
An interface cannot provide any code at all
An interface can only define public static final constants
An interface cannot define instance variables
Adding a new method has ripple effects on implementing classes (design maintenance)
JAXB cannot deal with interfaces
An interface cannot extends or implement an abstract class
All interface methods are public
In general, interfaces should be used to define contracts (what is to be achieved, not how to achieve it).
Abstract Class:
A class can extend at most one abstract class
An abstract class can contain code
An abstract class can define both static and instance constants (final)
An abstract class can define instance variables
Modification of existing abstract class code has ripple effects on extending classes (implementation maintenance)
Adding a new method to an abstract class has no ripple effect on extending classes
An abstract class can implement an interface
Abstract classes can implement private and protected methods
Abstract classes should be used for (partial) implementation. They can be a mean to restrain the way API contracts should be implemented.
Interface is used when you have scenario that all classes has same structure but totally have different functionality.
Abstract class is used when you have scenario that all classes has same structure but some same and some different functionality.
Take a look the article : http://shoaibmk.blogspot.com/2011/09/abstract-class-is-class-which-cannot-be.html
There are a lot of great answers here, but I often find using BOTH interfaces and abstract classes is the best route. Consider this contrived example:
You're a software developer at an investment bank, and need to build a system that places orders into a market. Your interface captures the most general idea of what a trading system does,
1) Trading system places orders
2) Trading system receives acknowledgements
and can be captured in an interface, ITradeSystem
public interface ITradeSystem{
public void placeOrder(IOrder order);
public void ackOrder(IOrder order);
}
Now engineers working at the sales desk and along other business lines can start to interface with your system to add order placement functionality to their existing apps. And you haven't even started building yet! This is the power of interfaces.
So you go ahead and build the system for stock traders; they've heard that your system has a feature to find cheap stocks and are very eager to try it out! You capture this behavior in a method called findGoodDeals(), but also realize there's a lot of messy stuff that's involved in connecting to the markets. For example, you have to open a SocketChannel,
public class StockTradeSystem implements ITradeSystem{
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
The concrete implementations are going to have lots of these messy methods like connectToMarket(), but findGoodDeals() is all the traders actually care about.
Now here's where abstract classes come into play. Your boss informs you that currency traders also want to use your system. And looking at currency markets, you see the plumbing is nearly identical to stock markets. In fact, connectToMarket() can be reused verbatim to connect to foreign exchange markets. However, findGoodDeals() is a much different concept in the currency arena. So before you pass off the codebase to the foreign exchange wiz kid across the ocean, you first refactor into an abstract class, leaving findGoodDeals() unimplmented
public abstract class ABCTradeSystem implements ITradeSystem{
public abstract void findGoodDeals();
#Override
public void placeOrder(IOrder order);
getMarket().place(order);
#Override
public void ackOrder(IOrder order);
System.out.println("Order received" + order);
private void connectToMarket();
SocketChannel sock = Socket.open();
sock.bind(marketAddress);
<LOTS MORE MESSY CODE>
}
Your stock trading system implements findGoodDeals() as you've already defined,
public class StockTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
deals = <apply magic wizardry>
System.out.println("The best stocks to buy are: " + deals);
}
but now the FX whiz kid can build her system by simply providing an implementation of findGoodDeals() for currencies; she doesn't have to reimplement socket connections or even the interface methods!
public class CurrencyTradeSystem extends ABCTradeSystem{
public void findGoodDeals();
ccys = <Genius stuff to find undervalued currencies>
System.out.println("The best FX spot rates are: " + ccys);
}
Programming to an interface is powerful, but similar applications often re-implement methods in nearly identical ways. Using an abstract class avoids reimplmentations, while preserving the power of the interface.
Note: one may wonder why findGreatDeals() isn't part of the interface. Remember, the interface defines the most general components of a trading system. Another engineer may develop a COMPLETELY DIFFERENT trading system, where they don't care about finding good deals. The interface guarantees that the sales desk can interface to their system as well, so it's preferable not to entangle your interface with application concepts like "great deals".
Which should you use, abstract classes or interfaces?
Consider using abstract classes if any of these statements apply to your use case:
You want to share code among several closely related classes.
You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
Consider using interfaces if any of these statements apply to your use case:
You expect that unrelated classes would implement your interface.
For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
You want to take advantage of multiple inheritance of type.
New methods added regularly to interface by providers, to avoid issues extend Abstract class instead of interface.
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
Things have been changed a lot in last three years with addition of new capabilities to interface with Java 8 release.
From oracle documentation page on interface:
An interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.
As you quoted in your question, abstract class is best fit for template method pattern where you have to create skeleton. Interface cant be used here.
One more consideration to prefer abstract class over interface:
You don't have implementation in base class and only sub-classes have to define their own implementation. You need abstract class instead of interface since you want to share state with sub-classes.
Abstract class establishes "is a" relation between related classes and interface provides "has a" capability between unrelated classes.
Regarding second part of your question, which is valid for most of the programming languages including java prior to java-8 release
As always there is a trade-off, an interface gives you freedom with regard to the base class, an abstract class gives you the freedom to add new methods later. – Erich Gamma
You can’t go and change an Interface without having to change a lot of other things in your code
If you prefer abstract class to interface earlier with above two considerations, you have to re-think now as default methods have added powerful capabilities to interfaces.
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
To select one of them between interface and abstract class, oracle documentation page quote that:
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.
Refer to these related questions fore more details:
Interface vs Abstract Class (general OO)
How should I have explained the difference between an Interface and an Abstract class?
In summary : The balance is tilting more towards interfaces now.
Are there any other scenarios, besides those mentioned above, where specifically we require to use abstract class (one is see is template method design pattern is conceptually based on this only)?
Some design patterns use abstract classes (over interfaces) apart from Template method pattern.
Creational patterns:
Abstract_factory_pattern
Structural patterns:
Decorator_pattern
Behavioral patterns:
Mediator_pattern
You are not correct. There are many scenarios. It just isn't possible to reduce it to a single 8-word rule.
The shortest answer is, extend abstract class when some of the functionalities uou seek are already implemented in it.
If you implement the interface you have to implement all the method. But for abstract class number of methods you need to implement might be fewer.
In template design pattern there must be a behavior defined. This behavior depends on other methods which are abstract. By making sub class and defining those methods you actually define the main behavior. The underlying behavior can not be in a interface as interface does not define anything, it just declares. So a template design pattern always comes with an abstract class. If you want to keep the flow of the behavior intact you must extend the abstract class but don't override the main behavior.
In my opinion, the basic difference is that an interface can't contain non-abstract methods while an abstract class can.
So if subclasses share a common behavior, this behavior can be implemented in the superclass and thus inherited in the subclasses
Also, I quoted the following from "software architecture design patterns in java" book
" In the Java programming language, there is no support for multiple inheritance.
That means a class can inherit only from one single class. Hence inheritance
should be used only when it is absolutely necessary. Whenever possible, methods
denoting the common behavior should be declared in the form of a Java interface to be implemented by different implementer classes. But interfaces suffer from the limitation that they cannot provide method implementations. This means that every implementer of an interface must explicitly implement all methods declared in an interface, even when some of these methods represent the invariable part of the functionality and have exactly the same implementation in all of the implementer classes. This leads to redundant code. The following example demonstrates how the Abstract Parent Class pattern can be used in such cases without requiring redundant method implementations."
Abstract classes are different from interfaces in two important aspects
they provide default implementation for chosen methods (that is covered by your answer)
abstract classes can have state (instance variables) - so this is one more situation you want to use them in place of interfaces
This is a good question The two of these are not similar but can be use for some of the same reason, like a rewrite. When creating it is best to use Interface. When it comes down to class, it is good for debugging.
This is my understanding, hope this helps
Abstract classes:
Can have member variables that are inherited (can’t be done in interfaces)
Can have constructors (interfaces can’t)
Its methods can have any visibility (ie: private, protected, etc - whereas all interface methods are public)
Can have defined methods (methods with an implementation)
Interfaces:
Can have variables, but they are all public static final variables
constant values that never change with a static scope
non static variables require an instance, and you can’t instantiate an interface
All methods are abstract (no code in abstract methods)
all code has to be actually written in the class that implements the particular interface
Usage of abstract and interface:
One has "Is-A-Relationship" and another one has "Has-A-Relationship"
The default properties has set in abstract and extra properties can be expressed through interface.
Example: --> In the human beings we have some default properties that are eating, sleeping etc. but if anyone has any other curricular activities like swimming, playing etc those could be expressed by Interface.
Abstract classes should be extended when you want to some common behavior to get extended. The Abstract super class will have the common behavior and will define abstract method/specific behavior which sub classes should implement.
Interfaces allows you to change the implementation anytime allowing the interface to be intact.
I think the answers here are missing the main point:
Java interfaces (the question is about Java but there are similar mechanisms in other languages) is a way to partially support multiple inheritance, i.e. method-only inheritance.
It is similar to PHP's traits or Python's duck typing.
Besides that, there is nothing additional that you truly need an interface for --and you cannot instantiate a Java interface.
This question already has answers here:
What is the difference between an interface and abstract class?
(38 answers)
Closed 8 years ago.
Conceptually I know the difference between abstract class and interface. But wondering about the technical difference between these two. Why Sun made this interface term even though I can have fully abstract class and make my work done.
Read here http://javarevisited.blogspot.kr/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html
Difference between abstract class and interface in Java
Abstract Class vs Interface in Java and When to use them over otherWhile deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java.
1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language.
2) Java interface can extend multiple interface also Java class can implement multiple interfaces, Which means interface can provide more polymorphism support than abstract class . By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where class extends Canvas and implements CommandListener to provide both graphic and event-handling functionality..
3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.
I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find all those syntactical differences.
Read more: http://javarevisited.blogspot.com/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html#ixzz31l59K92Z
you are free to choose interface or abstract class in the above scenario
but keep below things in mind
if you made a fully abstract class then
your subclass will extend one class to implement that behaviour and
its not eligible to extend any other class as multiple inheritance is not supported in java.
see without interface we cant achieve multiple inheritance.
Now if we approach interface instead of fully abstract class
then class can implement it and still eligable for extension of one more class.
so choose fully abstract class in your design if your sub classes can never need to extend any other class.
if sub classes need to extend some classes later (usually its how we need in application) then choose interface.
You write a java program with interfaces, abstract class and concrete class but do not mention any constructor, compile it and see byte codes in .class files. You would see as expected abstract class and concrete classes have default constructor added by compiler where as interfaces do not get constructor added to it by compiler. This should help you understand technical differences as I believe you know other differences.
I might receive downvotes for this answer :) . Consider this scenario.
public class TestClass{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish f = new Fish();
f.walk();
}
}
abstract class Animal {
protected void walk() {
System.out.println("walking");
}
}
class Fish extends Animal {
}
O/ P : walking
Technically a fish can't walk. Still since it extends the Animal class, it "can" walk which is wrong from a design perspective(even though Fish doesn't implement walk(), it can still call it).. If Animal were to be an Interface, then Fish must implement the method walk() which it won't / shouldn't. So, you will be forced to relook at the design.
Because you can have a class implement 2 interfaces, but you can't have a class implement (or extend) 2 abstract classes.
An abstract class can have some implementation code and instance variables. An interface has only method signatures and static variable definitions, no implementation code.
Further, if you implement an interface you must include implementation code for all of the methods defined in the interface.
In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.
I believe overriding methods in subclasses/implementations is possible in both cases, therefore, what is the real advantage of one over the other (interfaces vs abstract classes in Java)?
Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."
Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."
Abstract classes have some serious drawbacks. For example:
class House {
}
class Boat {
}
class HouseBoat extends /* Uh oh!! */ {
// don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}
You can get through via an interface:
interface Liveable {
}
interface Floatable {
}
class HouseBoat implements Liveable, Floatable {
}
Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)
And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.
Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).
Abstract classes are useful when you need concrete behaviour from the base class.
The facts are-
Java doesn't support multiple inheritance
Multiple interfaces can be implemented
Few methods in an abstract class may be implemented
These facts can be used to tilt the advantage in favor of interfaces or abstract classes.
If there are more than one behavior that a class must share with other classes, interfaces win.
If a method definition has to be shared/ overridden with other classes, abstract classes win.
An class may implement several interfaces, whereas it may only extend one class (abstract or concrete), because Java does not support multiple inheritance.
In OOP (mostly independent of a concrete language) abstract classes are a re-use mechanism for the class hierarchy for behaviour and structure which isn't complete on its own.
Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation.
All other differences are technical details, important is different usage.
You dont override an interface. You implement it.
Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.
Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.
-Method without any implementation is abstract method,whenever a class contains one or more abstract method,then it must be declared as a abstract class
-Interface is fully abstract which cannot have constructor,instance and static blocks,and it contains only two types of members
1.public abstract method
2.public-static-final variable
*Both cannot be instantiated but reference can be created.
*Which one suits better depends on the application
-Interfaces are useful because Java classes will not support multiple inheritance but interfaces do.
-Abstract classes are useful when you need concrete behavior from the base class.
The main advantages of interface over abstract class is to overcome the occurrence of diamond
problem and achieve multiple inheritance.
In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java.
So to achieve multiple inheritance we use interface .
class Animal
{ void move(){} }
class Bird
{ void move(){fly} }
class Fish
{ void move(){swim} }
Now, if class Animal is abstract class like
Animal a;
a= new Bird(); or a = new Fish()
Here, abstraction works well, but if there are 100 objects like Animal a[100];
You can not write new Bird().move or new Fish().move 100 times
Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked
Second it supports multiple inheritance as class A can implements as many interfaces.
Amazing answers!!
I too want to put my opinion on Interface.
As the name says it is interface which means it will provide interface between two classes.
It help a class or interface hold multiple behavior at the same time.
Who ever having the interface can access the behavior of the class agreed with the interface.
interface teacher
{
//methods related to teacher
}
interface student
{
//methods related to student
}
interface employee
{
//methods related to employee
}
class Person:teacher,student,employee
{
//definition of all the methods in teacher,student, employee interface
//and method for person
}
Now here which ever class is having teacher interface will have access to only teacher behavior of Person.
Similarly the class or module having student interface will have access to only student behavior of person.
Using abstract class, it is not at all possible.
Hope this will add some additional points. :)
Happy coding!!.
What is the difference between an abstract class and an interface?
Interfaces are stateless. They cannot gave variables, though they can have constants.
Also, interfaces provide the 'design by contract ' capability.
Abstract classes force a concrete implementation, where interfaces allow more flexibility because any class that implements that interface can be substituted at run time.
Also, since interfaces simply describe behavior that is exposed, not the implementation, then thet allow for multiple inheritance.
Also abstract classes are more a design convenience as they provide for compiler enforcement in that subclasses must implement abstract methods.
Interfaces and abstract classes are related, but serve different purposes.
At runtime the type of object is checked and the corresponding class method invoked.
This is also called late binding.
This is done by the runtime VM not by the programmer thus taking that If Else test out of your program code. So, your code is more flexible and does not depend on the class type to resolve the correct method to call. Thus us also called polymorphism.
An abstract class can have methods implemented. An interface cannot. Also a class can only extend one abstract class, but can implement many interfaces.
Use of interface : 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.
One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java (other than java.lang.Object, the root class of the Java type system) must have exactly one base class; multiple inheritance of classes is not allowed. Furthermore, a Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.
Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface.
Difference bw abstract class and interface : Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. An abstract class can contain no abstract methods also. A Java Interface can contain only method declarations and public static final constants and doesn't contain their implementation. The classes which implement the Interface must provide the method definition for all the methods present. An abstract class means the class must be extended. An abstract class must be extended by first concrete class in the inheritance tree. In the abstract class we can have both declaration and definition of a method but in interfaces there are only method signatures, no definition at all. An interface is like a 100% pure abstract class. A class can extend only one class but can implement multiple interfaces. Interfaces provides multiple inheritance without causing deadly diamond of death problem.
Extensive discussions here :
Abstract classes and interfaces in C#
Do/can abstract classes replace interfaces?
Disadvantage : when you have an 1000 class implementing an interface in your library, tomorrow if you want to have an additional method in interface , then changes should be reflected everywhere
This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 5 years ago.
In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?
Not always:
a class can extend only one class
a class can implement more than one interface
Sun docs make a more detailed comparison:
Abstract Classes versus Interfaces
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
In some cases you can use an abstract class instead of interface. However, it is hardly ever a good idea to do so. In general you should use the rule:
Interfaces specify behaviour.
Abstract classes specify implementation.
The other "problem" with using abstract classes is that you can then no longer implement mixins, that is you can implement multiple interfaces, however you can only extend one abstract class.
One point missing from the answers here is the idea of who will be implementing the interface.
If your component wants to return instances of abstract types to its callers, where the concrete types are defined internally and hidden from callers, use an interface. Conversely, if your component consumes or accepts instances of abstract types that its callers must implement, abstract classes are usually a better choice.
Anticipating evolution and maintaining binary compatibility tips the scales here. With an abstract class, you can add methods and, if you provide a base implementation, existing implementations of the abstract class will continue to work fine. With an interface, adding a method breaks binary compatibility, for no existing implementation could possibly continue to compile properly without changing to define the new method.
The Apache Cactus project has a good discussion on how to resolve these obligations.
To answer your question, yes you could use an abstract class (providing no implementation) instead of an interface but I'd consider this bad practice:
You've used up your "one-shot" at inheritance (without gaining any benefit).
You cannot inherit from multiple abstract classes but you can implement multiple interfaces.
I would advocate the use of abstract classes more in situations where you wish to provide a partial implementation of a class, possibly delegating some behavior to concrete subclass implementations.
A class in java can inherit from multiple interfaces, but only from one abstract class.
An interface cannot define any code, in an abstract class, you can define code (i.e. default behaviour of methods)
Abstract classes and interfaces are complementary.
For instance when creating an API you will want to present interfaces to the client, so that you may always completely change the implementation whereas he does not have to change its code and the user does not rely on implementation when building using your API but just on methods contracts.
Then you will have abstract classes partly implementing these interfaces, in order to
share some common code, which might be used in all (or almost all) implementations for interface, which is obvious
provide default behaviour which could be overridden in 'real' implementations, for instance a toString() method using interfaces methods to create a textual representation of the implementation
preserve implementations compatibility after interface changes, for instance when you add a new method in your interface, you also add a default implementation in the abstract class so that implementations (for instance those made by the user) extending the abstract class still work without changes
Interfaces are much cleaner and light weight. Abstract classes make you dependent on it heavily as you cannot extend any other classes.
Have a look at the interesting article "Why extends is evil" to get an idea about the differences between interface implementation and class inheritance (beside the obvious multi- single restrictions)
Abstract classes are the partial implementation of Abstraction while Interfaces are the fully implementation of Abstraction.Means in Abstract classes we can put methods declaration as well as method body.
We can't create an object of Abstract classes(association) and reuse the class by inheritence(not by association).
By default in interfaces all declared variables are static final and All methods are public.
For Example: In JDK there are only few abstract classes and HttpServlet is one of them which is used in Servlet.So we can't create object of HttpServlet and it can be used only by inheritence.
Main use of interface is when you create the reference of interface and call the method of particular class that's resolved at runtime. So it's always better idea to create reference of interface to call the method.
Interfaces can only hold abstract method, also interfaces can implement multiple interfaces to any class. But an abstract hold abstract and non abstract methods, and abstract methods cannot extend to more then one class.