Any good examples of inheriting from a concrete class? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Background:
As a Java programmer, I extensively inherit (rather: implement) from interfaces, and sometimes I design abstract base classes. However, I have never really felt the need to subclass a concrete (non-abstract) class (in the cases where I did it, it later turned out that another solution, such as delegation would have been better).
So now I'm beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate. For one thing, the Liskov substitution principle (LSP) seems almost impossible to satisfy for non-trivial classes; also many other questions here seem to echo a similar opinion.
So my question:
In which situation (if any) does it actually make sense to inherit from a concrete class?
Can you give a concrete, real-world example of a class that inherits from another concrete class, where you feel this is the best design given the constraints? I'b be particularly interested in examples that satisfy the LSP (or examples where satisfying LSP seems unimportant).
I mainly have a Java background, but I'm interested in examples from any language.

You often have a skeletal implementations for an interface I. If you can offer extensibility without abstract methods (e.g. via hooks), it is preferable to have a non-abstract skeletal class because you can instantiate it.
An example would be a forwarding wrapper classes, to be able to forward to another object of a concrete class C implementing I, e.g. enabling decoration or simple code-reuse of C without having to inherit from C. You can find such an example in Effective Java item 16, favor composition over inheritance. (I do not want to post it here because of copyrights, but it is really simply forwarding all method calls of I to the wrapped implementation).

I think the following is a good example when it can be appropriate:
public class LinkedHashMap<K,V>
extends HashMap<K,V>
Another good example is inheritance of exceptions:
public class IllegalFormatPrecisionException extends IllegalFormatException
public class IllegalFormatException extends IllegalArgumentException
public class IllegalArgumentException extends RuntimeException
public class RuntimeException extends Exception
public class Exception extends Throwable

One very common case I can think of is to derive from basic UI controls, such as forms, textboxes, comboboxes, etc. They are complete, concrete, and well able to stand on their own; however, most of them are also very basic, and sometimes their default behavior isn't what you want. Virtually nobody, for instance, would use an instance of an unadulterated Form, unless possibly they were creating an entirely dynamic UI layer.
For example, in a piece of software I wrote that recently reached relative maturity (meaning I ran out of time to focus primarily on developing it :) ), I found I needed to add "lazy loading" capability to ComboBoxes, so it wouldn't take 50 years (in computer years) for the first window to load. I also needed the ability to automatically filter the available options in one ComboBox based on what was shown in another, and lastly I needed a way to "mirror" one ComboBox's value in another editable control, and make a change in one control happen to the other as well. So, I extended the basic ComboBox to give it these extra features, and created two new types: LazyComboBox, and then further, MirroringComboBox. Both are based on the totally serviceable, concrete ComboBox control, just overriding some behaviors and adding a couple others. They're not very loosely-coupled and therefore not too SOLID, but the added functionality is generic enough that if I had to, I could rewrite either of these classes from scratch to do the same job, possibly better.

Generally speaking, the only time I derive from concrete classes is when they're in the framework. Deriving from Applet or JApplet being the trivial example.

This is an example of a current implementation that I'm undertaking.
In OAuth 2 environment, since the documentation is still in draft stage, the specification keeps changing (as of time of writing, we're in version 21).
Thus, I had to extend my concrete AccessToken class to accommodate the different access tokens.
In earlier draft, there was no token_type field set, so the actual access token is as follows:
public class AccessToken extends OAuthToken {
/**
*
*/
private static final long serialVersionUID = -4419729971477912556L;
private String accessToken;
private String refreshToken;
private Map<String, String> additionalParameters;
//Getters and setters are here
}
Now, with Access tokens that returns token_type, I have
public class TokenTypedAccessToken extends AccessToken {
private String tokenType;
//Getter and setter are here...
}
So, I can return both and the end user is none the wiser. :-)
In Summary: If you want a customized class that has the same functionality of your concrete class without changing the structure of the concrete class, I suggest extending the concrete class.

I mainly have a Java background, but I'm interested in examples from any language.
Like many frameworks, ASP.NET makes heavy use of inheritance to share behaviour between classes. For example, HtmlInputPassword has this inheritance hierarchy:
System.Object
System.Web.UI.Control
System.Web.UI.HtmlControls.HtmlControl // abstract
System.Web.UI.HtmlControls.HtmlInputControl // abstract
System.Web.UI.HtmlControls.HtmlInputText
System.Web.UI.HtmlControls.HtmlInputPassword
in which can be seen examples of concrete classes being derived from.
If you're building a framework - and you're sure you want to do that - you may well finding yourself wanting a nice big inheritance hierarchy.

Other use case would be the to override the default behavior:
Lets say there is a class which uses standard Jaxb parser for parsing
public class Util{
public void mainOperaiton(){..}
protected MyDataStructure parse(){
//standard Jaxb code
}
}
Now say I want to use some different binding (Say XMLBean) for the parsing operation,
public class MyUtil extends Util{
protected MyDataStructure parse(){
//XmlBean code code
}
}
Now I can use the new binding with code reuse of super class.

The decorator pattern, a handy way of adding additional behaviour to a class without making it too general, makes heavy use of inheritance of concrete classes. It was mentioned here already, but under somewhat a scientific name of "forwarding wrapper class".

Lot of answers but I though I'd add my own $0.02.
I override concreate classes infrequently but under some specific circumstances. At least 1 has already been mentioned when framework classes are designed to be extended. 2 additional ones come to mind with some examples:
1) If I want to tweak the behavior of a concrete class. Sometimes I want to change how the concrete class works or I want to know when a certain method is called so I can trigger something. Often concrete classes will define a hook method whose sole usage is for subclasses to override the method.
Example: We overrode MBeanExporter because we need to be able to unregister a JMX bean:
public class MBeanRegistrationSupport {
// the concrete class has a hook defined
protected void onRegister(ObjectName objectName) {
}
Our class:
public class UnregisterableMBeanExporter extends MBeanExporter {
#Override
protected void onUnregister(ObjectName name) {
// always a good idea
super.onRegister(name);
objectMap.remove(name);
}
Here's another good example. LinkedHashMap is designed to have its removeEldestEntry method overridden.
private static class LimitedLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
#Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
return size() > 1000;
}
2) If a class shares a significant amount of overlap with the concrete class except for some tweaks to functionality.
Example: My ORMLite project handles persisting Long object fields and long primitive fields. Both have almost the identical definition. LongObjectType provides all of the methods that describe how the database deals with long fields.
public class LongObjectType {
// a whole bunch of methods
while LongType overrides LongObjectType and only tweaks a single method to say that handles primitives.
public class LongType extends LongObjectType {
...
#Override
public boolean isPrimitive() {
return true;
}
}
Hope this helps.

Inheriting concrete class is only option if you want to extend side-library functionality.
For example of real life usage you can look at hierarchy of DataInputStream, that implements DataInput interface for FilterInputStream.

I'm beginning to feel that there is almost no situation where inheriting from a concrete class is appropriate.
This is one 'almost'. Try writing an applet without extending Applet or JApplet.
Here is an e.g. from the applet info. page.
/* <!-- Defines the applet element used by the appletviewer. -->
<applet code='HelloWorld' width='200' height='100'></applet> */
import javax.swing.*;
/** An 'Hello World' Swing based applet.
To compile and launch:
prompt> javac HelloWorld.java
prompt> appletviewer HelloWorld.java */
public class HelloWorld extends JApplet {
public void init() {
// Swing operations need to be performed on the EDT.
// The Runnable/invokeLater() ensures that happens.
Runnable r = new Runnable() {
public void run() {
// the crux of this simple applet
getContentPane().add( new JLabel("Hello World!") );
}
};
SwingUtilities.invokeLater(r);
}
}

Another good example would be data storage types. To give a precise example: a red-black tree is a more specific binary tree, but retrieving data and other information like size can be handled identical. Of course, a good library should have that already implemented but sometimes you have to add specific data types for your problem.
I am currently developing an application which calculates matrices for the users. The user can provide settings to influence the calculation. There are several types of matrices that can be calculated, but there is a clear similarity, especially in the configurability: matrix A can use all the settings of matrix B but has additional parameters which can be used. In that case, I inherited from the ConfigObjectB for my ConfigObjectA and it works pretty good.

In general, it is better to inherit from an abstract class than from a concrete class. A concrete class must provide a definition for its data representation, and some subclasses will need a different representation. Since an abstract class does not have to provide a data representation, future subclasses can use any representation without fear of conflicting with the one that they inherited.
Even i never found a situation where i felt concrete inheritence is neccessary. But there could be some situations for concrete inheritence specially when you are providing backward compatibility to your software. In that case u might have specialized a class A but you want it to be concrete as your older application might be using it.

Your concerns are also echoed in the classic principle "favor composition over inheritance", for the reasons you stated. I can't remember the last time I inherited from a concrete class. Any common code that needs to be reused by child classes almost always needs to declare abstract interfaces for those classes. In this order I try to prefer the following strategies:
Composition (no inheritance)
Interface
Abstract Class
Inheriting from a concrete class really isn't ever a good idea.
[EDIT] I'll qualify this statement by saying I don't see a good use case for it when you have control over the architecture. Of course when using an API that expects it, whaddaya gonna do? But I don't understand the design choices made by those APIs. The calling class should always be able to declare and use an abstraction according to the Dependency Inversion Principle. If a child class has additional interfaces to be consumed you'd either have to violate DIP or do some ugly casting to get at those interfaces.

from the gdata project:
com.google.gdata.client.Service is designed to act as a base class that can be customized for specific types of GData services.
Service javadoc:
The Service class represents a client connection to a GData service. It encapsulates all protocol-level interactions with the GData server and acts as a helper class for higher level entities (feeds, entries, etc) that invoke operations on the server and process their results.
This class provides the base level common functionality required to access any GData service. It is also designed to act as a base class that can be customized for specific types of GData services. Examples of supported customizations include:
Authentication - implementing a custom authentication mechanism for services that require authentication and use something other than HTTP basic or digest authentication.
Extensions - define expected extensions for feed, entry, and other types associated with a the service.
Formats - define additional custom resource representations that might be consumed or produced by the service and client side parsers and generators to handle them.

I find the java collection classes as a very good example.
So you have an AbstractCollection with childs like AbstractList, AbstractSet, AbstractQueue...
I think this hierarchy has been well designed.. and just to ensure there's no explosion there's the Collections class with all its inner static classes.

You do that for instance in GUI libraries. It makes not much sense to inherit from a mere Component and delegate to a Panel. It is likely much easyer to inherit from the Panel directly.

Just a general thought. Abstract classes are missing something. It makes sense if this, what is missing, is different in each derived class. But you may have a case where you don't want to modify a class but just want to add something. To avoid duplication of code you would inherit. And if you need both classes it would be inheritance from a concrete class.
So my answer would be: In all cases where you really only want to add something. Maybe this just doesn't happen very often.

Related

Can I create a non-abstract method in an interface that will be called by every implementation? [duplicate]

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.

The importance of interfaces in Java [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Let's say we have two classes, Tiger and Aeroplane.
One thing in common for these two types is the Speed. I know that it would be illogical to create a superclass ClassWithSpeed and then derive subclasses Aeroplane and Tiger from it.
Instead, it is better to create an interface that contains the method speed() and then implement it in Aeroplane and Tiger. I get that. But, we can do the same thing without interfaces. We could define method speed() in Aeroplane and method speed() in Tiger.
The only (maybe very big) flaw it would be that we couldn't "reach" the objects of Tiger and Aeroplane through an interface reference.
I am beginner in Java and OOP, and I would be very grateful if someone explained to me the role of interfaces.
Cheers!
It's:
public int howFast(Airplane airplane) {
return airplane.speed();
}
public int howFast(Tiger tiger) {
return tiger.speed();
}
public int howFast(Rocket rocket) {
return rocket.speed();
}
public int howFast(ThingThatHasntBeenInventedYet thingx) {
// wait... what? HOW IS THIS POSSIBLE?!
return thingx.speed();
}
...
vs
public int howFast(Mover mover) {
return mover.speed();
}
Now, imagine having to go back and change all those howFast functions in the future.
Interface or no, each class will have to implement or inherit the speed() method. An interface lets you use those disparate classes more easily, because they've each promised to behave in a certain way. You'll call speed(), and they'll return an int, so you don't have to write separate methods for every possible class.
When you find you need to handle speed differently because of a breakthrough in relativistic physics, you only need to update the methods that call speed(). When your great-granddaughter writes a class for HyperIntelligentMonkeyFish, she doesn't have to disassemble your ancient binary and make changes so that your code can monitor and control her mutant army. She needs only declare that HyperIntelligentMonkeyFish implements Mover.
Interfaces allow Java, since it is statically typed, to work around multiple inheritance limitations to the degree felt worthwhile by the language designers.
In a dynamic language (like Python, Ruby, etc.) you can just call the speed method on any arbitrary object and discover at runtime if it is there or not.
Java, on the other hand, is statically typed, which means the compiler has to agree that the method will be there ahead of time. The only way to do that on classes that don't share common ancestry, and may only have Object in common, is an interface.
Since objects can implement an arbitrary number of interfaces, this means you get the goodness of multiple inheritance (a single object that can pose as multiple different objects for different methods) without the downside (of conflicting implementations in the two super classes).
With Java 8, the designers of the language concluded that interfaces without any implementation was overly restrictive (they didn't like my solution I guess ;-)), so they allow for a default implementation, thus expanding the multi-inheritance options of interfaces, while still trying to avoid the conflicting implementation problem via a complex set of precedence rules so that there is an unambiguous default implementation to execute.
I am trying to explain the advantage of interface with the following example-
suppose you have another class where you need to use the tiger or AeroPlane as parameter. So by using interface you can call using
someObject.someMethod(ClassWithSpeed)
but if you dont use interface you can use
someObject.someMethod(Tiger)
someObject.someMethod(AeroPlane)
Now what should you do? Your probable answer will be like, "I will use two overloaded method".
This is okay so far, But
Say you need to add more options (say car, cycle, rabbit, tortoise.... 100 others). So what will you do to make the change of your existing code?? you will need to change a lots of things..
The overall example above has only one purpose. That is to say
"we need interface to create a better, reusable and properly object oriented
design"
N.B.
if you are sure the program is too small and you will never need to change them then I think it is okay to implement without interface
Defining an interface allows you to define methods that work not only on Aeroplane and Tiger, but also other classes that share the same interface.
For example, say your interface is IObjectWithSpeed. Then you can define a method like this -- in a single class that operates on IObjectWithSpeed objects.
public double calculateSecondsToTravel( IObjectWithSpeed obj, double distance ) {
return distance / obj.getSpeed();
}
Interfaces allow us to satisfy the open/closed principle - open for extension, but closed for modification. The single implementation of the method above doesn't need to be modified as new classes are defined that implement IObjectWithSpeed.
I want go into much theoretical details but will try to explain using this example.
Consider JDBC API. It is API used to deal with database related options in the Java. Now, there are so many databases in the industry. How would one write drivers for that? Well, the quick and dirty approach may be write own implementation using our own classes and API.
But think from the programmer's perspective. Will they start learning DATABASE DRIVER's API while using different database? The answer is NO.
So what is the solution to the problem ? Just have a well defined API which anyone can extend for his own implementation.
In JDBC API, there are some Interfaces which are Connection, ResultSet, PreparedStatement, Statement etc. Now each database vendor will implement the interface and will write his own implementation for that. Result ? : Reduced effort from the developer and easy understandability.
Now, what this custom implementation might consisting of ? It's simple. They do what, take ResultSet interface for example and implement it and in whatever method the ResultSet is gettting returned, return THE CLASS THAT IMPLEMENTS ResultSet interface like this
ResultSet rs=new ResultSetImpl(); //this is what they are doing internally.
So interface are like contracts. They define what your class is able to do and they give your application flexibility. You can create your own APIs using interfaces properly.
Hope this helps you.
An interface is not simply a method signature.
It is a type that represents a contract. The contract is the thing, not the method signatures. When a class implements an interface, it is because there is a contract for a shared behavior that the class has an interest in implementing as a type. That contract is implemented via the specified members which are usually method bodies but may also include static final fields.
It may be true that a tiger and an aeroplane both could be expressed as a type with a common behavior implemented through speed() ... and if so, then the interface represents the contract for expressing that behavior.
Aside from being descriptive for those classes' functionality, methods of an interface could be used without any knowledge about the classes implementing it, even for classes that were not yet defined.
So for example, if you'd need a class Transport that computes say efficient routes, it could be given a class that implements ClassWithSpeed as a parameter and use its method speed() for computing what it needs. This way you could use it with our class Aeroplane, but also with any class we define later, say Boat. Java will take care that if you want to use a class as a parameter to Transport it will implement ClassWithSpeed, and that any class implementing ClassWithSpeed implements the method speed() so that it can be used.
The interface (as a language construct) is used by the compiler to prove that the method call is valid and allows you to have dependent classes interact with the implementing class while having the least possible knowledge about the implementing class.
This is a very wide question to give a simple answer. I can recommend a book Interface Oriented Design: With Patterns. It explains all power of interfaces. And why we should not avoid them.
Have you tried using composition instead?, if I want 2 dissimilar classes to inherit the same abilities I use a class which takes an object of the type its working with by using abstract classes and checking the instances. Interfaces are useful for forcing methods to be including in the class but don't require any implementation or for 2 teams of coders to work on different coding areas.
Class Tiger {
public MovingEntity mover;
public Tiger(){
mover.speed=30;
mover.directionX=-1;
mover.move(mover);
}
}
Class Plane {
public MovingEntity mover;
public Plane(){
mover.speed=500;
mover.directionX=-1;
mover.move(mover);
}
Abstract Class Moverable(){
private int xPos;
private int yPos;
private int directionX;
private int directionY;
private int speed;
Class MovingEntity extends Moverable {
public void move(Moverable m){
if(m instanceof Tiger){
xPos+=directionX*speed;
yPos+=directionY*speed;
}else if(m instanceof Plane){
xPos+=directionX*speed;
yPos+=directionY*speed;
}
}
On language level, the only use of interfaces is, like you mentioned, to be able to refer to different classes in a common way. On people level, however, the picture looks different: IMO Java is strong when used in big projects where the design and the implementation are done by separate people, often from separate companies. Now, instead of writing a specification on a Word document, the system architects can create a bunch of classes that implementers can then directly insert in their IDEs and start working on them.
In other words it is more convenient instead of declaring that "Class X implements methods Y and Z in order for it to be used for purpose A, just to say that "Class X implements interface A"
Because creating interface gives you Polymorphism, across all those classes i.e. Tiger and Aeroplane.
You can extend from an (abstract or concrete) class when the base class's functionality is going to be the core of your child class's functionality as well.
You use interfaces when you want to add an augmented functionality to your class in addition to its core functionality. So using interfaces would give you Polymorphism even when its not your class's core functionality (because you've entered a contract by implementing the interface). This is a huge advantage over creating a speed() method with each class.

Java Code Style -- Interfaces vs. Abstract Classes

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

Java: extending Object class

I'm writing (well, completing) an "extension" of Java which will help role programming.
I translate my code to Java code with javacc. My compilers add to every declared class some code. Here's an example to be clearer:
MyClass extends String implements ObjectWithRoles { //implements... is added
/*Added by me */
public setRole(...){...}
public ...
/*Ends of stuff added*/
...//myClass stuff
}
It adds Implements.. and the necessary methods to EVERY SINGLE CLASS you declare. Quite rough, isnt'it?
It will be better if I write my methods in one class and all class extends that.. but.. if class already extends another class (just like the example)?
I don't want to create a sort of wrapper that manage roles because i don't want that the programmer has to know much more than Java, few new reserved words and their use.
My idea was to extends java.lang.Object.. but you can't. (right?)
Other ideas?
I'm new here, but I follow this site so thank you for reading and all the answers you give! (I apologize for english, I'm italian)
If it is only like a "research" project in which you want to explore how such extension would work, you could provide your own implementation of the Object class. Simply copy the existing object implementation, add your setRole method etc, and give -Xbootclasspath:.:/usr/lib/jvm/java-6-sun/jre/lib/rt.jar as parameter to the java command. (I will look for api-classes in . before looking in the real rt.jar.)
You should consider using composition rather than inheritence to solve this problem; that way you can provide the functionality you need without using up your "one-shot" at inheritence.
For example, the JDK provides a class PropertyChangeSupport, which can be used to manage PropertyChangeListeners and the firing of PropertyChangeEvents. In situations where you wish to write a class that fires PropertyChangeEvents you could embed a PropertyChangeSupport instance variable and delegate all method calls to that. This avoids the need for inheritence and means you can supplement an existing class hierarchy with new functionality.
public class MyClass extends MySuperClass {
private final PropertyChangeSupport support;
public MyClass() {
this.support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
protected void firePropertyChangeEvent() {
PropertyChangeEvent evt = new ...
support.firePropertyChangeEvent(evt);
}
}
you can extend Object - every class extends it.
you seem to need something like multiple inheritance - there isn't such a thing in Java
if you want to add functionality, use object composition. I.e.,
YourClass extends Whatever implements ObjectWithRoles {
private RoleHandler roleHandler;
public RoleHandler getRoleHandler() {..} // defined by the interface
}
And then all of the methods are placed in the RoleHandler
If you're talking about adding a role to all your objects I would also consider an annotation-based solution. You'd annotate your classes with something like #Role("User"). In another class you can extract that role value and use it.
I think it would need an annotation with runtime retention and you can check, run-time, whether the annotation is present using reflection and get that annotation using getAnnotation. I feel that this would be a lot cleaner than extending all your classes automatically.
I believe there are some frameworks which use exactly such a solution, so there should be example code somewhere.
If you are doing what you are doing, then inheritance is probably not the correct idiom. You may want to consider the decorator pattern, whereby you construct a class that takes as its parameter some other class with less functionality, and adds some additional functionality to it, delegating to the existing class for functionality that already exists. If the implementation is common to many of your decorators, you may want to consider putting that functionality in class that can be shared and to which you can delegate for all your decorators. Depending on what you need, double-dispatch or reflection may be appropriate in order to make similar but not quite the same decorators for a large variety of classes.
Also, as has been pointed out in the comments, String is declared "final" and, therefore, cannot be extended. So, you should really consider a solution whereby you delegate/decorate objects. For example, you might have some object that wraps a string and provides access to the string via getString() or toString(), but then adds the additional functionality on top of the String class.
If you just want to associate some objects with additional attributes, use a Map (e.g. HashMap).
What you really want to do would be monkey patching, i.e. changing the behaviour of existing classes without modifying their code.
Unfortunately, Java does not support this, nor things like mixins that might be used alternatively. So unless you're willing to switch to a more dynamic language like Groovy, you'll have to live with less elegant solutions like composition.

Why are interfaces preferred to abstract classes?

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

Categories