choosing interface or abstract class - java

In an interview it was asked to me to justify when to choose interface and when to choose abstract classes and in which conditions you will choose out of the two only one.. I have come up with my analysis for interface and that is...
Interface is best choice for Type declaration or defining contract
between multiple parties.
If multiple programmers are working in different modules of a project they still use each others API by defining interface and not waiting
for actual implementation to be ready.
This brings us a lot of flexibility and speed in terms of coding and
development. Use of Interface also ensures best practices like
"programming for interfaces than implementation" and results in more
flexible and maintainable code.
But I don't have strong reasons to justify the abstract classes, Please advise..!

Abstract classes are used to group a number of concrete classes under one entity.
For example, take the abstract class Animal.
Animal is not something concrete. it's a family of, well, animals. but they all share certain aspectes, for example, each has a speak() option (well, except fish and sort). but each one implements it differently. this way you can override just the methods which are not the same, for example sleep() or breath() are common (again, fish are differnet :) ).
Interfaces on the other hand are more direct definition of an 'action'. That's why most (if not all) the interfaces in Java ends with 'able' (Comprable, Serializable...)
By implementing the interface, you're telling other programmers or who ever uses your code that this class can do this and this.
A dog, for example, is not, Animable.
Basically, to sum it up, I think that the best definition is this.
Use abstract classes when you have a class that A is kind of B and interface when A can do B.
Hope that's help.

Abstract classes are used when you want to provide partial implementation.

Abstract classes can have default behaviour(implementation) if is required, interfaces cannot.
An abstract class can provide default behaviour for ALL methods or no methods whereas interfaces cannot.
Abstract classes can have state shared with all subclasses, interfaces don't specify state.
You can implement multiple interfaces, you can only extend one (abstract) class.

An interface declares a contract with whatever implements it. It's a guarantee that the class will contain the methods in the interface.
An abstract class is similar in that anything that subclasses it will also have to implement the abstract methods, but you can also have working methods with code in them.
I use interfaces a lot for callbacks with Android programming. Abstract classes I use a lot if I have a lot of similar data to display and just want small changes to implementation. Use an abstract class to cut down on repeated code while still having different implementation.

You are correct on your definition of interfaces.
Abstract classes should serve a completely different purpose. As an example, let's say you are implementing several classes for an animal simulator. 'Animal' defines several behaviours that could already have a basic implementation, but is not itself something that would make sense to have instantiated. Likewise for 'Mamal', a bubclass of 'Animal'. Only a subclass 'Tiger' would not be abstract, but most of what a tiger does that's not tiger specific would be implemented in it's abstract superclasses.

1. If speaking generally, An Abstract class will be needed when we need to force down some features on the Sub-Class from Super-Class, letting the Sub-Class to have the flexibility to add other functinality.
Eg:
Let Car be the Abstract Super-Class, which has 4 Tyres, 1 Steering ,etc...
Now the Sub classes like Santro i10, Maruti-800, Mahindr Bolero etc are Sub classes,
but they need to have 4 Tyres, 1 Steering to be called a car, not they can have a radio or not as an additional feature.
2. Interface was introduced in java, because there is no Multiple Inheritance.
3. Interface is more about providing a role.
Eg:
Let Dog be the Super-Class.
Wild Dogs and Pet Dogs are Sub-Classes.
Wild Behavior and Pet Behavior are Interfaces
Now as both Wild Dog and Pet Dog are dogs, but with different behavious. Then they must implement the Wild Behavior or Pet Behavior respectively

you'd want to use an abstract class when you want your classes to only implement the methods if the situation would call for them.
an example would be if you had a super class vehicle and you wanted your sub-classes to give you number of wheels if they have them. You wouldn't need them if they were boats so the contract would force you to implement still while you could just out right ignore it for your abstract class.

Related

What is difference between abstract class with all abstract methods and interface(not technically)

I've been wondering what is the difference between them? Is it only in this: abstract class declares what an object is and interface says what object can do? Or there is something more deeper? Thanks.
Whether it can have fields, whether it can have a constructor, whether any of those methods can be protected/package-private/private, whether subtypes can inherit from other abstract classes/interfaces...that about covers it.
The statement "abstract class declares what an object is" refers to the rule that says that a class may inherit from a base class if it has an "is a" relationship to the base class. So, a Sedan may inherit from Car because a Sedan "is a" Car. But that's only part of the story. Usually, we define abstract base classes to inherit from when we want the abstract base class to contain some functionality that restricts derived classes in what they can do, often by exposing final methods which cannot be overridden. So, a hypothetical mail delivery abstract base class may offer a public final prepareAndSend() method which invokes abstract overridables on itself called stuffEnvelope(), lickEnvelope(), mailEnvelope(), in that order. The derived class may override those methods, but it has no power to change the order in which they will be invoked because prepareAndSend() is final. You can't impose such restrictions with interfaces.
Interfaces, on the other hand, describe "capabilities" or "aspects" that an object may have. An object may have many different capabilities, so it may implement many interfaces.
Note that it may seem that the "is a" relationship can apply to interfaces, but it either only happens in certain contrived examples, or it is an illusion caused by the liberal syntax of the English language; it is not generalizable, in many cases it is not even factual, and that's the reason why there is no rule that says that an object should have an "is a" relationship with each interface that it implements.
So, someone may of course make an "ICar" interface, there is nothing wrong with that, in which case there will inevitably be something that "is a Car", but what you are more likely to see is interfaces like "IDrivable", "IInsurable", "ITaxable", "IFuelConsumer", etc. all of which describe traits. The fact that you can then say "a car is a taxable" is a fluke of the English language; a car does not actually bear an "is a" relationship with "taxable" because "taxable" is not even a thing. So then, whoever came up with that "ICar" usually just meant it as a convenience to combine all the characteristics of a car into one common interface.
In Java, there are no pure abstract classes. A class that declares only abstract methods has concrete methods also, because it is a subclass -- directly or indirectly -- of the concrete Object class.
An interface is a better choice for defining an abstract API. Java allows classes to extend at most one class, but implement multiple interfaces.
From the Java tutorial Abstract Methods and Classes (line breaks added):
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.
The tutorial also recommends cases when an abstract class or interface are desirable. Paraphrased, it recommends abstract classes when you want to share code or non-static, non-final fields, or use access qualifiers other than public. Usually none of these will apply to a pure abstract class.
It recommends interfaces when you want to specify an API that may be implemented by multiple unrelated classes, or want to take advantage of multiple inheritance of interface types.

Should I Program to an Interface or an Abstract Base Class? What exactly does that phrase mean?

In object oriented programming, I have read that you should program to an interface not an implementation but do they mean literal interfaces (no shared code at all)?
Is it okay to program to an abstract base class that would have been an interface except that there were variables in this "interface" that all sub-classes were expected to have? Replicating a variable across sub-classes would have been an inconvenience because if I changed the name of one of the variables in one of the sub-classes I would have to change the name of that variable in all of the sub-classes.
In following the principle of "program to an interface not an implementation", is this okay or would you create another interface on top of the abstract base class and program to that interface?
You want to program to interfaces because it means lower coupling. Note that interfaces in Java are more flexible since they can be implemented by a class anywhere in the class hierarchy unlike abstract classes (as a result of single inheritance). Such flexibility means that your code is reusable to a higher degree.
The important point of "programming to an interface not an implementation" is that of the general principles mentioned above, even if they might cause some minor inconveniences.
Also, even if you program to an interface, you can always implement said interface (or parts of it) by means of abstract classes if you'd like, achieving both low coupling and code reusability at the same time.
It's always okay to program to abstract or even concrete classes, however it's better if you can avoid it.
This discussion might be helpful or this one and of course this one.
Note: C++ doesn't have interfaces. You might argue it doesn't need them.
you should program to an interface not an implementation but do they mean literal interfaces (no shared code at all)?
Possibly. Where it makes sense to do this, it can work very well. Note: in Java interfaces can have code as well.
Is it okay to program to an abstract base class that would have been an interface except that there were variables in this "interface" that all sub-classes were expected to have?
If you need fields in the implementation an abstract class can make sense. You can still use an interface as well.
Replicating a variable across sub-classes would have been an inconvenience because if I changed the name of one of the variables in one of the sub-classes I would have to change the name of that variable in all of the sub-classes.
This is where using an IDE helps. You can change a field, class, method name in all your code with one action.
is this okay or would you create another interface on top of the abstract base class and program to that interface?
You can code your implementation to an abstract class, but the users of that class should be using an interface if possible.
e.g. HashMap extends AbstractMap but implements Map. Most people would use Map not AbstractMap

Extending an object vs Implementing an interface

Trying to understand a question I got wrong on a test:
How does inheritance differ from implementing interfaces?
With inheritance, a class gains behavior from its superclass.
With interfaces, a class gains behavior from the interface it implements. (this is the one I chose)
With inheritance, a class must implement the methods defined by its superclass.
With interfaces, a class gains both instance variables and behaviors from the interface it implements.
The way I was thinking is that interfaces define behavior, while superclasses define characteristics... or are they the same? Or am I completely backwards in my understanding?
Edit: I guess I should specify that I do know the difference between interfaces and inheritance. I'm just wondering about the two options which use the term behavior. I don't know if the prof was nitpicking about terminology, or if he asked the question poorly.
I know that when you implement an interface, you have to implement all the methods as defined in the interface. As such, I would say that the interface defines the behavior that a class must have, but extending another superclass (although it does also define some behaviors (more can be given to the subclass), it doesn't seem to fit as strongly as the interface defining behaviors. If the class implements an interface, you can be sure that it has certain behaviors.
Maybe the question was meant to ask whether or not the interface itself has the code for the behavior, or if it's just the definition - which if worded that way, I would have known the answer.
I think some of your misunderstanding might stem purely from semantics. Perhaps a more straightforward way of describing an interface is that it defines an API but does not provide an implementation of that API. One caveat is that I will use Java for my example but in a language like C++, implementing an interface is inheritance of a special sort - namely inheriting from a class consisting of pure virtual functions.
In Java, for instance, you might have an EventListener interface defined as:
public interface IEventListener {
public void handleEvent(Event event);
}
The interface does not, to use the question's verbiage, say anything about how a class that implements the IEventListener interface will behave when it receives an event it only ensures that any class implementing this interface will have the characteristic of being able to receive an event of type Event.
Inheritance, on the other hand, allows super classes to also inherit behavior (implementation). For instance, consider the following Java base class:
public abstract BaseClass {
public void baseMethod(int value) {
System.out.println(int);
}
public class SubClass extends BaseClass {
}
Any class that inherits from BaseClass gains both the API (characteristics) of BaseClass and also the implementation (behavior). In other words not only can you invoke instanceOfSubClass.baseMethod(1), a characteristic, doing so will result in the behavior defined in the BaseClass, namely 1 being printed to the console.
So your answer (2) is incorrect because interfaces do not specify behavior (implementation) only API (characteristics). Inheritance can handle both.
I think the point of the question is to explain that inheritance is specifically useful when you want to share behavior and not just API. That said, implementation (behavior) can also be shared via composition and such a strategy is often better - see Item 16 in Bloch's Effective Java for an excellent discussion.
When you implement an Interface, you don't necessarily care much for the implementation. Also remember that you can implement as many interfaces as you want, since they only specify contracts but not how to fulfill them. The creator of the interface lets you take care of that.
When you extend an Object it's usually because you need some functionality which an already existing object already got the majority of, but will only need that bit extra. Or you want to redefine some of the existing behaviour of an already existing object.
To give you the answer: 1 is right. You don't HAVE to implement the methods of a superclass (Inheritance). Only when it's abstract the next subclass of this superclass needs to implement the methods (like in an interface).
An object implementing an x Interface tells the object that it must do all actions (methods) listed in the definition of an interface. So in the object that implements x, you need to implements all actions. An interface cannot be instanciated.
But when you inherit from an object y, the object y may already have an implementation of some actions. if not the method will be marked as abstract (in java) and you need to implement it in your inherited object.
This is a very common OO design question in Java.
Sincerely recommend this very good article on this topic that explains it well:
http://www.javaworld.com/javaqa/2001-04/03-qa-0420-abstract.html
The correct answer is 1. The answer you chose (option 2) is wrong because interfaces technically do not have any behavior. They are just a list of abstract methods. You can consider them more as a template on which you can base your classes. For example, suppose a project is split into two parts, which need to be integrated at the end. Each team could use a common interface to base their classes on, so that integration would be a much easier job.
with inheritance, you get a cat. with an interface, you get the skeleton of a cat.
You gain behavior and implementation from inheritance. Remember that a subclass inherits all non-constructor and private methods from it's superclass. This means that you may inherit functionality (implementation) of certain methods.
With implementation you gain just behavior. All you are doing with implementation is signing a contract with the compiler, saying that you promise to override all abstract methods defined in the implemented class or interface.
I hope this helped.

Abstract class vs Interface in Java

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.

Why is having an abstract subclass of concrete class bad design?

After all ANY java abstract is an abstract subclass of Object. Sometimes we need to force the subclass to implement some methods, but may already have a pretty well defined hierarchy with concrete classes.
For example: I have a well functioning hierarchy with
Vehicle<--- Car
and now I want to add ElectricCar to this hierarchy.
vehicle<--Car<--ElectricCar.
I also want all the different types of electric cars to implement certain behaviors like getBatteryLife or something-
Why would it be a bad idea to make ElectricCar abstract ?
there's nothing wrong in making it abstract. if your business requires you to make it abstract, it's fine. Like you said, lots of classes in Java lib are abstract and still extending Object.
It's not bad, per se. Not common, but not bad. The only thing I can think of is understandability: if I saw a concrete class Car that I could instantiate, I would normally assume that any child of it was also instantiable, because 99% of code works this way.Then I'd be confused, for a second, about not being able to instantiate an ElectricCar.
It could be argued that this pattern breaks the Liskov Substituion Principle since you can't pass "ElectricCar" wherever "Car" is expected if it's declared abstract (you could pass instances of ElectricCar subclasses of course).
In this particular example, the concrete electric cars (hydrogen powered/plug-in/etc?) I would expect to inherit directly from "Car" since they satisfy an "is-a" relationship and are a proper specialisation of "Car". If you wanted to described some common behaviours and traits they should provide then they should also implement an ElectricCar interface.
It seems what you really want is the ability to inherit from Car (since that is what they are) and share/re-use common implementations of electric car related methods. In this case you are looking at a multiple inheritance problem or a need for mixins, neither of which are directly supported in Java.
Providing an abstract class in the middle of a concrete hierarchy may be one way around this, but it's not pretty.
Personally I would prefer to define an Interface for ElectricCar and then allow the implementing class to define the methods. Then you can share the behavior of getBatteryLife through another mechanism.
I've built some pretty deep hierarchies of Inheritance and I tend to avoid them do to the brittle nature they tend to build up over time. One Base class might make sense, but I would think about how you can compose your object model to share behavior w/o inheritance if possible.
In you example I would say that supposedly the Car class should be abstract (or an interface), too. But there is nothing wrong with the ElectricCar being abstract.

Categories

Resources