I am going through some Java code and I see lots of abstract classes which contain nothing in them.
For eg. something like this -
public abstract class Processor
{
}
They have concrete implementation classes though. In what situations would such abstract classes make sense?
IMO, an abstract class is preferred over an interface when you want to create a base class with behaviors and state common to all the subclasses. I am not sure of any situation where an empty abstract class would be more useful than an interface. Usually, the marker interfaces are the ones that are empty.
Abstract classes are used when you have some logic which would be common to all possible implementing classes.
Writing an Abstract class with nothing inside and different classes extending it is pretty much useless.The only difference is that you can use the same handle for all the concrete classes.
One of the situation would be, if you don't want your class instantiated using new keyword, then you can define it is abstract.
In some libraries, they will look for implementation of these marker abstract classes using reflection. Also this is kind of a documentation for your code by abstract class name itself.
Related
An abstract class can have both abstract and non abstract method. Class have only abstract methods can called absolutely abstract class.
There is no advantage of one over the other.
One approach allows you to share implementation code.
The other approach allows you to not share implementation code.
You use whichever is more appropriate to the task that you are doing.
If abstract class still has their childs and child has their own behaviors also some behaviors are common, in that case we sud go for non absolutely abstract class
I am looking into abstract classes and interfaces.
Can someone tell me if there is a difference between a fully abstract class and an interface?
Google is your friend, so use it.
There certainly are differences. The first few that I can think of are
You can not inherit multiple abstract classes, where you can implement multiple interfaces
You can write a decorator for an interface but not for an abstract class
You can provide default implementations in an abstract class, but not in an interface. This allows to extend an abstract class in a backwards compatible way, which is not possible with an interface
An abstract class can contain method implementation while an interface can't.
In Interface :
you can only declare the variables, Methods but no defination is written in this interface
Abstract class :
while a class is declared as Abstract class then the declarations may or may not include abstract methods.In abstract class we can write the definitions also. Unlike interfaces, abstract classes can contain fields that are not static and final.
Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation.
READ THE JAVA DOCUMENTATION!
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).
There is a difference between a fully abstract class and an interface?
If all methods are abstract the behaviour is almost (not exactly) the same, but yes there are differences. Mainly because a class can't extends from multiple (abstract or not) classes but can implements many interfaces. Also the fields can't be private in an interface.
Note that the Oracle documentation suggest to turn fully abstract class into interface.
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:
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.