When should I write interface and abstract class [duplicate] - java

I have recently had two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.
From my experience I think the following is true. If I am missing a major point please let me know.
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass.
Only Events, Delegates, Properties (C#) and Methods can exist in an Interface. A class can implement multiple Interfaces.
Abstract Class:
Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. An Abstract class can also have class variables besides Events, Delegates, Properties and Methods. A class can implement one abstract class only due to the non-existence of Multi-inheritance in C#.
After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?
Another interviewer asked me, "What if you had a Public variable inside the interface, how would that be different than in a Abstract Class?" I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.
See Also:
When to use an interface instead of an abstract class and vice versa
Interfaces vs. Abstract Classes
How do you decide between using an Abstract Class and an Interface?
What is the difference between an interface and abstract class?

How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF (US Air Force) pilot. At that point I wasn't qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn't required to be a safety officer, other people could have done it as well.
All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots 'are' USAF pilots. Anyone can be a safety officer. So, to summarize:
Pilot: abstract class
C-141 Pilot: concrete class
ISafety Officer: interface
added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.

While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.
In .NET (similar for Java):
interfaces can have no state or implementation
a class that implements an interface must provide an implementation of all the methods of that interface
abstract classes may contain state (data members) and/or implementation (methods)
abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).
As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.
Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

I think the answer they are looking for is the fundamental or OPPS philosophical difference.
The abstract class inheritance is used when the derived class shares the core properties and behaviour of the abstract class. The kind of behaviour that actually defines the class.
On the other hand interface inheritance is used when the classes share peripheral behaviour, ones which do not necessarily define the derived class.
For eg. A Car and a Truck share a lot of core properties and behaviour of an Automobile abstract class, but they also share some peripheral behaviour like Generate exhaust which even non automobile classes like Drillers or PowerGenerators share and doesn't necessarily defines a Car or a Truck, so Car, Truck, Driller and PowerGenerator can all share the same interface IExhaust.

Short: Abstract classes are used for Modelling a class hierarchy of similar looking classes (For example Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes)
AND
Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface(e.g. Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter if you can eat , you can swim you can die or anything.. it matters only a thing that you need to have Height (implementation in you class) ).

There are a couple of other differences -
Interfaces can't have any concrete implementations. Abstract base classes can. This allows you to provide concrete implementations there. This can allow an abstract base class to actually provide a more rigorous contract, wheras an interface really only describes how a class is used. (The abstract base class can have non-virtual members defining the behavior, which gives more control to the base class author.)
More than one interface can be implemented on a class. A class can only derive from a single abstract base class. This allows for polymorphic hierarchy using interfaces, but not abstract base classes. This also allows for a pseudo-multi-inheritance using interfaces.
Abstract base classes can be modified in v2+ without breaking the API. Changes to interfaces are breaking changes.
[C#/.NET Specific] Interfaces, unlike abstract base classes, can be applied to value types (structs). Structs cannot inherit from abstract base classes. This allows behavioral contracts/usage guidelines to be applied on value types.

Inheritance
Consider a car and a bus. They are two different vehicles. But still, they share some common properties like they have a steering, brakes, gears, engine etc.
So with the inheritance concept, this can be represented as following ...
public class Vehicle {
private Driver driver;
private Seat[] seatArray; //In java and most of the Object Oriented Programming(OOP) languages, square brackets are used to denote arrays(Collections).
//You can define as many properties as you want here ...
}
Now a Bicycle ...
public class Bicycle extends Vehicle {
//You define properties which are unique to bicycles here ...
private Pedal pedal;
}
And a Car ...
public class Car extends Vehicle {
private Engine engine;
private Door[] doors;
}
That's all about Inheritance. We use them to classify objects into simpler Base forms and their children as we saw above.
Abstract Classes
Abstract classes are incomplete objects. To understand it further, let's consider the vehicle analogy once again.
A vehicle can be driven. Right? But different vehicles are driven in different ways ... For example, You cannot drive a car just as you drive a Bicycle.
So how to represent the drive function of a vehicle? It is harder to check what type of vehicle it is and drive it with its own function; you would have to change the Driver class again and again when adding a new type of vehicle.
Here comes the role of abstract classes and methods. You can define the drive method as abstract to tell that every inheriting children must implement this function.
So if you modify the vehicle class ...
//......Code of Vehicle Class
abstract public void drive();
//.....Code continues
The Bicycle and Car must also specify how to drive it. Otherwise, the code won't compile and an error is thrown.
In short.. an abstract class is a partially incomplete class with some incomplete functions, which the inheriting children must specify their own.
Interfaces
Interfaces are totally incomplete. They do not have any properties. They just indicate that the inheriting children are capable of doing something ...
Suppose you have different types of mobile phones with you. Each of them has different ways to do different functions; Ex: call a person. The maker of the phone specifies how to do it. Here the mobile phones can dial a number - that is, it is dial-able. Let's represent this as an interface.
public interface Dialable {
public void dial(Number n);
}
Here the maker of the Dialable defines how to dial a number. You just need to give it a number to dial.
// Makers define how exactly dialable work inside.
Dialable PHONE1 = new Dialable() {
public void dial(Number n) {
//Do the phone1's own way to dial a number
}
}
Dialable PHONE2 = new Dialable() {
public void dial(Number n) {
//Do the phone2's own way to dial a number
}
}
//Suppose there is a function written by someone else, which expects a Dialable
......
public static void main(String[] args) {
Dialable myDialable = SomeLibrary.PHONE1;
SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....
Hereby using interfaces instead of abstract classes, the writer of the function which uses a Dialable need not worry about its properties. Ex: Does it have a touch-screen or dial pad, Is it a fixed landline phone or mobile phone. You just need to know if it is dialable; does it inherit(or implement) the Dialable interface.
And more importantly, if someday you switch the Dialable with a different one
......
public static void main(String[] args) {
Dialable myDialable = SomeLibrary.PHONE2; // <-- changed from PHONE1 to PHONE2
SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....
You can be sure that the code still works perfectly because the function which uses the dialable does not (and cannot) depend on the details other than those specified in the Dialable interface. They both implement a Dialable interface and that's the only thing the function cares about.
Interfaces are commonly used by developers to ensure interoperability(use interchangeably) between objects, as far as they share a common function (just like you may change to a landline or mobile phone, as far as you just need to dial a number). In short, interfaces are a much simpler version of abstract classes, without any properties.
Also, note that you may implement(inherit) as many interfaces as you want but you may only extend(inherit) a single parent class.
More Info
Abstract classes vs Interfaces

If you consider java as OOP language to answer this question, Java 8 release causes some of the content in above answers as obsolete. Now java interface can have default methods with concrete implementation.
Oracle website provides key differences between interface and abstract class.
Consider using abstract classes if :
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.
Consider using interfaces if :
You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
In simple terms, I would like to use
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Have a look at code example to understand things in clear way : How should I have explained the difference between an Interface and an Abstract class?

The interviewers are barking up an odd tree. For languages like C# and Java, there is a difference, but in other languages like C++ there is not. OO theory doesn't differentiate the two, merely the syntax of language.
An abstract class is a class with both implementation and interface (pure virtual methods) that will be inherited. Interfaces generally do not have any implementation but only pure virtual functions.
In C# or Java an abstract class without any implementation differs from an interface only in the syntax used to inherit from it and the fact you can only inherit from one.

By implementing interfaces you are achieving composition ("has-a" relationships) instead of inheritance ("is-a" relationships). That is an important principle to remember when it comes to things like design patterns where you need to use interfaces to achieve a composition of behaviors instead of an inheritance.

These answers are all too long.
Interfaces are for defining behaviors.
Abstract classes are for defining a thing itself, including its behaviors. That's why we sometimes create an abstract class with some extra properties inheriting an interface.
This also explains why Java only supports single inheritance for classes but puts no restriction on interfaces. Because a concrete object can not be different things, but it can have different behaviors.

Conceptually speaking, keeping the language specific implementation, rules, benefits and achieving any programming goal by using anyone or both, can or cant have code/data/property, blah blah, single or multiple inheritances, all aside
1- Abstract (or pure abstract) Class is meant to implement hierarchy. If your business objects look somewhat structurally similar, representing a parent-child (hierarchy) kind of relationship only then inheritance/Abstract classes will be used. If your business model does not have a hierarchy then inheritance should not be used (here I am not talking about programming logic e.g. some design patterns require inheritance). Conceptually, abstract class is a method to implement hierarchy of a business model in OOP, it has nothing to do with Interfaces, actually comparing Abstract class with Interface is meaningless because both are conceptually totally different things, it is asked in interviews just to check the concepts because it looks both provide somewhat same functionality when implementation is concerned and we programmers usually emphasize more on coding. [Keep this in mind as well that Abstraction is different than Abstract Class].
2- an Interface is a contract, a complete business functionality represented by one or more set of functions. That is why it is implemented and not inherited. A business object (part of a hierarchy or not) can have any number of complete business functionality. It has nothing to do with abstract classes means inheritance in general. For example, a human can RUN, an elephant can RUN, a bird can RUN, and so on, all these objects of different hierarchy would implement the RUN interface or EAT or SPEAK interface. Don't go into implementation as you might implement it as having abstract classes for each type implementing these interfaces. An object of any hierarchy can have a functionality(interface) which has nothing to do with its hierarchy.
I believe, Interfaces were not invented to achieve multiple inheritances or to expose public behavior, and similarly, pure abstract classes are not to overrule interfaces but Interface is a functionality that an object can do (via functions of that interface) and Abstract Class represents a parent of a hierarchy to produce children having core structure (property+functionality) of the parent
When you are asked about the difference, it is actually conceptual difference not the difference in language-specific implementation unless asked explicitly.
I believe, both interviewers were expecting one line straightforward difference between these two and when you failed they tried to drove you towards this difference by implementing ONE as the OTHER
What if you had an Abstract class with only abstract methods?

i will explain Depth Details of interface and Abstract class.if you know overview about interface and abstract class, then first question arrive in your mind when we should use Interface and when we should use Abstract class.
So please check below explanation of Interface and Abstract class.
When we should use Interface?
if you don't know about implementation just we have requirement specification then we go with Interface
When we should use Abstract Class?
if you know implementation but not completely (partially implementation) then we go with Abstract class.
Interface
every method by default public abstract means interface is 100% pure abstract.
Abstract
can have Concrete method and Abstract method, what is Concrete method, which have implementation in Abstract class,
An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Interface
We cannot declared interface as a private, protected
Q. Why we are not declaring Interface a private and protected?
Because by default interface method is public abstract so and so that reason that we are not declaring the interface as private and protected.
Interface method
also we cannot declared interface as private,protected,final,static,synchronized,native.....
i will give the reason:
why we are not declaring synchronized method because we cannot create object of interface and synchronize are work on object so and son reason that we are not declaring the synchronized method
Transient concept are also not applicable because transient work with synchronized.
Abstract
we are happily use with public,private final static.... means no restriction are applicable in abstract.
Interface
Variables are declared in Interface as a by default public static final so we are also not declared variable as a private, protected.
Volatile modifier is also not applicable in interface because interface variable is by default public static final and final variable you cannot change the value once it assign the value into variable and once you declared variable into interface you must to assign the variable.
And volatile variable is keep on changes so it is opp. to final that is reason we are not use volatile variable in interface.
Abstract
Abstract variable no need to declared public static final.
i hope this article is useful.

For .Net,
Your answer to The second interviewer is also the answer to the first one... Abstract classes can have implementation, AND state, interfaces cannot...
EDIT: On another note, I wouldn't even use the phrase 'subclass' (or the 'inheritance' phrase) to describe classes that are 'defined to implement' an interface. To me, an interface is a definition of a contract that a class must conform to if it has been defined to 'implement' that interface. It does not inherit anything... You have to add everything yourself, explicitly.

Interface : should be used if you want to imply a rule on the components which may or may not be
related to each other
Pros:
Allows multiple inheritance
Provides abstraction by not exposing what exact kind of object is being used in the context
provides consistency by a specific signature of the contract
Cons:
Must implement all the contracts defined
Cannot have variables or delegates
Once defined cannot be changed without breaking all the classes
Abstract Class : should be used where you want to have some basic or default behaviour or implementation for components related to each other
Pros:
Faster than interface
Has flexibility in the implementation (you can implement it fully or partially)
Can be easily changed without breaking the derived classes
Cons:
Cannot be instantiated
Does not support multiple inheritance

I think they didn't like your response because you gave the technical differences instead of design ones. The question is like a troll question for me. In fact, interfaces and abstract classes have a completely different nature so you cannot really compare them. I will give you my vision of what is the role of an interface and what is the role of an abstract class.
interface: is used to ensure a contract and make a low coupling between classes in order to have a more maintainable, scalable and testable application.
abstract class: is only used to factorize some code between classes of the same responsability. Note that this is the main reason why multiple-inheritance is a bad thing in OOP, because a class shouldn't handle many responsabilities (use composition instead).
So interfaces have a real architectural role whereas abstract classes are almost only a detail of implementation (if you use it correctly of course).

Interface:
We do not implement (or define) methods, we do that in derived classes.
We do not declare member variables in interfaces.
Interfaces express the HAS-A relationship. That means they are a mask of objects.
Abstract class:
We can declare and define methods in abstract class.
We hide constructors of it. That means there is no object created from it directly.
Abstract class can hold member variables.
Derived classes inherit to abstract class that mean objects from derived classes are not masked, it inherit to abstract class. The relationship in this case is IS-A.
This is my opinion.

After all that, the interviewer came up with the question "What if you had an
Abstract class with only abstract methods? How would that be different
from an interface?"
Docs clearly say that if an abstract class contains only abstract method declarations, it should be declared as an interface instead.
An another interviewer asked me what if you had a Public variable inside
the interface, how would that be different than in Abstract Class?
Variables in Interfaces are by default public static and final. Question could be framed like what if all variables in abstract class are public? Well they can still be non static and non final unlike the variables in interfaces.
Finally I would add one more point to those mentioned above - abstract classes are still classes and fall in a single inheritance tree whereas interfaces can be present in multiple inheritance.

Copied from CLR via C# by Jeffrey Richter...
I often hear the question, “Should I design a base type or an interface?” The answer isn’t always clearcut.
Here are some guidelines that might help you:
■■ IS-A vs. CAN-DO relationship A type can inherit only one implementation. If the derived
type can’t claim an IS-A relationship with the base type, don’t use a base type; use an interface.
Interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong
with various object types, use an interface. For example, a type can convert instances of itself
to another type (IConvertible), a type can serialize an instance of itself (ISerializable),
etc. Note that value types must be derived from System.ValueType, and therefore, they cannot
be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship
and define an interface.
■■ Ease of use It’s generally easier for you as a developer to define a new type derived from a
base type than to implement all of the methods of an interface. The base type can provide a
lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
■■ Consistent implementation No matter how well an interface contract is documented, it’s
very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM
suffers from this very problem, which is why some COM objects work correctly only with
Microsoft
Word or with Windows Internet Explorer. By providing a base type with a good
default implementation, you start off using a type that works and is well tested; you can then
modify parts that need modification.
■■ Versioning If you add a method to the base type, the derived type inherits the new method,
you start off using a type that works, and the user’s source code doesn’t even have to be recompiled.
Adding a new member to an interface forces the inheritor of the interface to change
its source code and recompile.

tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.
Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.
ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?
Answer 2: Abstract classes can have a function body as partial/default implementation.
ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?
Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.
ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.
Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.
Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.
Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.
Coming to the UML Part. You should be familiar with below relationships:
Is A
Has A
Uses
Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?
Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.
When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car
{
MusicPlayer musicPlayer;
}
Now Honda doesn't manufacture music players. Or at least it’s not their main business.
So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.
This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.
You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.
Why can’t you create an object of abstract classes?
Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.
Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.
Why do interfaces allow multiple inheritance?
Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
MusicPlayer musicPlayer;
}
And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.

An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.
An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".
C# does allow for interface inheritance as well, mind you.

Most answers focus on the technical difference between Abstract Class and Interface, but since technically, an interface is basically a kind of abstract class (one without any data or implementation), I think the conceptual difference is far more interesting, and that might be what the interviewers are after.
An Interface is an agreement. It specifies: "this is how we're going to talk to each other". It can't have any implementation because it's not supposed to have any implementation. It's a contract. It's like the .h header files in C.
An Abstract Class is an incomplete implementation. A class may or may not implement an interface, and an abstract class doesn't have to implement it completely. An abstract class without any implementation is kind of useless, but totally legal.
Basically any class, abstract or not, is about what it is, whereas an interface is about how you use it. For example: Animal might be an abstract class implementing some basic metabolic functions, and specifying abstract methods for breathing and locomotion without giving an implementation, because it has no idea whether it should breathe through gills or lungs, and whether it flies, swims, walks or crawls. Mount, on the other hand, might be an Interface, which specifies that you can ride the animal, without knowing what kind of animal it is (or whether it's an animal at all!).
The fact that behind the scenes, an interface is basically an abstract class with only abstract methods, doesn't matter. Conceptually, they fill totally different roles.

Interfaces are light weight way to enforce a particular behavior. That is one way to think of.

As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface and Abstract class.
Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.
The below class acts as a base class for all the cars:
public class Cars
{
public string DigitalFuelMeter()
{
return "I have DigitalFuelMeter";
}
public string AirCondition()
{
return "I have AC";
}
public string SeatAdjust()
{
return "I can Adjust seat";
}
}
Consider we have a separate class for each Cars.
public class Alto : Cars
{
// Have all the features of Car class
}
public class Verna : Cars
{
// Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars
}
public class Cruze : Cars
{
// Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars
}
Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.
public abstract class Brake
{
public abstract string GetBrakeTechnology();
}
Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:
public class Verna : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.
interface IBrakeTechnology
{
string GetBrakeTechnology();
}
And the implementation is given below:
public class Verna : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.

1) An interface can be seen as a pure Abstract Class, is the same, but despite this, is not the same to implement an interface and inheriting from an abstract class. When you inherit from this pure abstract class you are defining a hierarchy -> inheritance, if you implement the interface you are not, and you can implement as many interfaces as you want, but you can only inherit from one class.
2) You can define a property in an interface, so the class that implements that interface must have that property.
For example:
public interface IVariable
{
string name {get; set;}
}
The class that implements that interface must have a property like that.

Though this question is quite old, I would like to add one other point in favor of interfaces:
Interfaces can be injected using any Dependency Injection tools where as Abstract class injection supported by very few.

From another answer of mine, mostly dealing with when to use one versus the other:
In my experience, interfaces are best
used when you have several classes
which each need to respond to the same
method or methods so that they can be
used interchangeably by other code
which will be written against those
classes' common interface. The best
use of an interface is when the
protocol is important but the
underlying logic may be different for
each class. If you would otherwise be
duplicating logic, consider abstract
classes or standard class inheritance
instead.

Interface Types vs. Abstract Base Classes
Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.
The interface type might seem very similar to an abstract base class. Recall
that when a class is marked as abstract, it may define any number of abstract members to provide a
polymorphic interface to all derived types. However, even when a class does define a set of abstract
members, it is also free to define any number of constructors, field data, nonabstract members (with
implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.
The polymorphic interface established by an abstract parent class suffers from one major limitation
in that only derived types support the members defined by the abstract parent. However, in larger
software systems, it is very common to develop multiple class hierarchies that have no common parent
beyond System.Object. Given that abstract members in an abstract base class apply only to derived
types, we have no way to configure types in different hierarchies to support the same polymorphic
interface. By way of example, assume you have defined the following abstract class:
public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
public abstract object Clone();
}
Given this definition, only members that extend CloneableType are able to support the Clone()
method. If you create a new set of classes that do not extend this base class, you can’t gain this
polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.
Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:
// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}
As you would guess, interface types come to the rescue. After an interface has been defined, it can
be implemented by any class or structure, in any hierarchy, within any namespace or any assembly
(written in any .NET programming language). As you can see, interfaces are highly polymorphic.
Consider the standard .NET interface named ICloneable, defined in the System namespace. This
interface defines a single method named Clone():
public interface ICloneable
{
object Clone();
}

Answer to the second question : public variable defined in interface is static final by default while the public variable in abstract class is an instance variable.

From Coding Perspective
An Interface can replace an Abstract Class if the Abstract Class has only abstract methods. Otherwise changing Abstract class to interface means that you will be losing out on code re-usability which Inheritance provides.
From Design Perspective
Keep it as an Abstract Class if it's an "Is a" relationship and you need a subset or all of the functionality. Keep it as Interface if it's a "Should Do" relationship.
Decide what you need: just the policy enforcement, or code re-usability AND policy.

For sure it is important to understand the behavior of interface and abstract class in OOP (and how languages handle them), but I think it is also important to understand what exactly each term means. Can you imagine the if command not working exactly as the meaning of the term? Also, actually some languages are reducing, even more, the differences between an interface and an abstract... if by chance one day the two terms operate almost identically, at least you can define yourself where (and why) should any of them be used for.
If you read through some dictionaries and other fonts you may find different meanings for the same term but having some common definitions. I think these two meanings I found in this site are really, really good and suitable.
Interface:
A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively.
Abstract:
Something that concentrates in itself the essential qualities of anything more extensive or more general, or of several things; essence.
Example:
You bought a car and it needs fuel.
Your car model is XYZ, which is of genre ABC, so it is a concrete car, a specific instance of a car. A car is not a real object. In fact, it is an abstract set of standards (qualities) to create a specific object. In short, Car is an abstract class, it is "something that concentrates in itself the essential qualities of anything more extensive or more general".
The only fuel that matches the car manual specification should be used to fill up the car tank. In reality, there is nothing to restrict you to put any fuel but the engine will work properly only with the specified fuel, so it is better to follow its requirements. The requirements say that it accepts, as other cars of the same genre ABC, a standard set of fuel.
In an Object Oriented view, fuel for genre ABC should not be declared as a class because there is no concrete fuel for a specific genre of car out there. Although your car could accept an abstract class Fuel or VehicularFuel, you must remember that your only some of the existing vehicular fuel meet the specification, those that implement the requirements in your car manual. In short, they should implement the interface ABCGenreFuel, which "... enables separate and sometimes incompatible elements to coordinate effectively".
Addendum
In addition, I think you should keep in mind the meaning of the term class, which is (from the same site previously mentioned):
Class:
A number of persons or things regarded as forming a group by reason of common attributes, characteristics, qualities, or traits; kind;
This way, a class (or abstract class) should not represent only common attributes (like an interface), but some kind of group with common attributes. An interface doesn't need to represent a kind. It must represent common attributes. This way, I think classes and abstract classes may be used to represent things that should not change its aspects often, like a human being a Mammal, because it represents some kinds. Kinds should not change themselves that 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.

Two classes with the same method Java [duplicate]

I've been reading a lot about interfaces and class inheritance in Java, and I know how to do both and I think I have a good feel for both. But it seems that nobody ever really compares the two side by side and explains when and why you would want to use one or the other. I have not found a lot of times when implementing an interface would be a better system than extending a superclass.
So when do you implement an interface and when do you extend a superclass?
Use an interface if you want to define a contract. I.e. X must take Y and return Z. It doesn't care how the code is doing that. A class can implement multiple interfaces.
Use an abstract class if you want to define default behaviour in non-abstract methods so that the endusers can reuse it without rewriting it again and again. A class can extend from only one other class. An abstract class with only abstract methods can be as good definied as an interface. An abstract class without any abstract method is recognizeable as the Template Method pattern (see this answer for some real world examples).
An abstract class in turn can perfectly implement an interface whenever you want to provide the enduser freedom in defining the default behaviour.
You should choose an interface if all you want is to define a contract i.e. method signatures that you want the inheriting classes to implement. An interface can have no implementation at all. The inheriting classes are free to choose their own implementation.
Sometimes you want to define partial implementation in a base type and want to leave the rest to inheriting classes. If that is the case, choose an abstract class. An abstract class can define method implementations and variables while leaving some methods as abstract. Extending classes can choose how to implement the abstract methods while they also have the partial implementation provided by the superclass.
One extreme of abstract classes is a pure abstract class - one that has only abstract methods and nothing else. If it comes to pure abstract class vs. an interface, go with the interface. Java allows only single implementation inheritance whereas it allows multiple interface inheritance meaning that a class can implement multiple interfaces but can extend only one class. So choosing a pure abstract class over the interface will mean that the subclass will not be allowed to extend any other class while implementing the abstract methods.
Use an interface to define behavior. User (abstract) classes (and subclasses) to provide implementation. They are not mutually exclusive; they can all work together.
For example, lets say you are defining a data access object. You want your DAO to be able to load data. So put a load method on the interface. This means that anything that wants to call itself a DAO must implement load. Now lets say you need to load A and B. You can create a generic abstract class that is parameterized (generics) to provide the outline on how the load works. You then subclass that abstract class to provide the concrete implementations for A and B.
The main reason for using abstract classes and interfaces are different.
An abstract class should be used when you have classes that have identical implementations for a bunch of methods, but vary in a few.
This may be a bad example, but the most obvious use of abstract classes in the Java framework is within the java.io classes. OutputStream is just a stream of bytes. Where that stream goes to depends entirely on which subclass of OutputStream you're using... FileOutputStream, PipedOutputStream, the output stream created from a java.net.Socket's getOutputStream method...
Note: java.io also uses the Decorator pattern to wrap streams in other streams/readers/writers.
An interface should be used when you just want to guarantee that a class implements a set of methods, but you don't care how.
The most obvious use of interfaces is within the Collections framework.
I don't care how a List adds/removes elements, so long as I can call add(something) and get(0) to put and get elements. It may use an array (ArrayList, CopyOnWriteArrayList), linked list (LinkedList), etc...
The other advantage in using interfaces is that a class may implement more than one. LinkedList is an implementation of both List and Deque.
No one?
http://mindprod.com/jgloss/interfacevsabstract.html
EDIT: I should supply more than a link
Here's a situation. To build on the car example below, consider this
interface Drivable {
void drive(float miles);
}
abstract class Car implements Drivable {
float gallonsOfGas;
float odometer;
final float mpg;
protected Car(float mpg) { gallonsOfGas = 0; odometer = 0; this.mpg = mpg; }
public void addGas(float gallons) { gallonsOfGas += gallons; }
public void drive(float miles) {
if(miles/mpg > gallonsOfGas) throw new NotEnoughGasException();
gallonsOfGas -= miles/mpg;
odometer += miles;
}
}
class LeakyCar extends Car { // still implements Drivable because of Car
public addGas(float gallons) { super.addGas(gallons * .8); } // leaky tank
}
class ElectricCar extends Car {
float electricMiles;
public void drive(float miles) { // can we drive the whole way electric?
if(electricMiles > miles) {
electricMiles -= miles;
odometer += miles;
return; // early return here
}
if(electricMiles > 0) { // exhaust electric miles first
if((miles-electricMiles)/mpg > gallonsOfGas)
throw new NotEnoughGasException();
miles -= electricMiles;
odometer += electricMiles;
electricMiles = 0;
}
// finish driving
super.drive(miles);
}
}
I think that interfaces work best when you use them to express that the object has a certain property or behavior, that spans multiple inheritance trees, and is only clearly defined for each class.
For example think of Comparable. If you wanted to create a class Comparable to be extended by other classes, it would have to be very high on the inheritance tree, possible right after Object, and the property it expresses is that two objects of that type can be compared, but there's no way to define that generally (you can't have an implementation of compareTo directly in the Comparable class, it's different for every class that implements it).
Classes work best when they define something clear, you know what properties and behaviors they have, and have actual implementations for methods, that you want to pass down to the children.
So classes work when you need to define a concrete object like a human, or a car, and interfaces work better when you need more abstract behavior that's too general to belong to any inheritance tree, like the ability to be compared (Comparable) or to be run (Runnable).
One method of choosing between an interface and a base class is the consideration of code ownership. If you control all the code then a base class is a viable option. If on the other hand many different companies might want to produce replaceable components, that is define a contract then an interface is your only choice.
I found some articles, particularly some who describe why you should not use implementation inheritance (i.e. superclasses):
Why extends is evil
Inheritance of implementation is evil
Implementation inheritance
Implementation inheritance
Java inheritance FAQ
I guess I'll give the classic car example.
When you have a car interface, you can create a Ford, a Chevy, and an Oldsmobile. In other words, you create different kinds of cars from a car interface.
When you have a car class, you can then extend the car class to make a truck, or a bus. In other words, you add new attributes to the sub classes while keeping the attributes of the base or super class.
You can think of extending from a super class if the derived class is of the same type.I mean that when a class extends an abstract class, they both should be of the same type, the only difference being that the super class has a more general behavior and the sub class has a more specific behavior. An interface is a totally different concept. When a class implements an interface, its either to expose some API(contract) or to get certain behavior. To give an example, I would say that Car is an abstract class. You can extend many classes from it like say Ford, Chevy and so on which are each of type car. But then if you need certain specific behavior like say you need a GPS in a car then the concrete class, eg Ford should implement GPS interface.
If you only want to inherit method signatures (name, arguments, return type) in the subclasses, use an interface, but if you also want to inherit implementation code, use a superclass.

Interface vs Abstract classes in project modules [duplicate]

I have recently had two telephone interviews where I've been asked about the differences between an Interface and an Abstract class. I have explained every aspect of them I could think of, but it seems they are waiting for me to mention something specific, and I don't know what it is.
From my experience I think the following is true. If I am missing a major point please let me know.
Interface:
Every single Method declared in an Interface will have to be implemented in the subclass.
Only Events, Delegates, Properties (C#) and Methods can exist in an Interface. A class can implement multiple Interfaces.
Abstract Class:
Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. An Abstract class can also have class variables besides Events, Delegates, Properties and Methods. A class can implement one abstract class only due to the non-existence of Multi-inheritance in C#.
After all that, the interviewer came up with the question "What if you had an Abstract class with only abstract methods? How would that be different from an interface?" I didn't know the answer but I think it's the inheritance as mentioned above right?
Another interviewer asked me, "What if you had a Public variable inside the interface, how would that be different than in a Abstract Class?" I insisted you can't have a public variable inside an interface. I didn't know what he wanted to hear but he wasn't satisfied either.
See Also:
When to use an interface instead of an abstract class and vice versa
Interfaces vs. Abstract Classes
How do you decide between using an Abstract Class and an Interface?
What is the difference between an interface and abstract class?
How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF (US Air Force) pilot. At that point I wasn't qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn't required to be a safety officer, other people could have done it as well.
All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots 'are' USAF pilots. Anyone can be a safety officer. So, to summarize:
Pilot: abstract class
C-141 Pilot: concrete class
ISafety Officer: interface
added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.
While your question indicates it's for "general OO", it really seems to be focusing on .NET use of these terms.
In .NET (similar for Java):
interfaces can have no state or implementation
a class that implements an interface must provide an implementation of all the methods of that interface
abstract classes may contain state (data members) and/or implementation (methods)
abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itself)
interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).
As general OO terms, the differences are not necessarily well-defined. For example, there are C++ programmers who may hold similar rigid definitions (interfaces are a strict subset of abstract classes that cannot contain implementation), while some may say that an abstract class with some default implementations is still an interface or that a non-abstract class can still define an interface.
Indeed, there is a C++ idiom called the Non-Virtual Interface (NVI) where the public methods are non-virtual methods that 'thunk' to private virtual methods:
http://www.gotw.ca/publications/mill18.htm
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface
I think the answer they are looking for is the fundamental or OPPS philosophical difference.
The abstract class inheritance is used when the derived class shares the core properties and behaviour of the abstract class. The kind of behaviour that actually defines the class.
On the other hand interface inheritance is used when the classes share peripheral behaviour, ones which do not necessarily define the derived class.
For eg. A Car and a Truck share a lot of core properties and behaviour of an Automobile abstract class, but they also share some peripheral behaviour like Generate exhaust which even non automobile classes like Drillers or PowerGenerators share and doesn't necessarily defines a Car or a Truck, so Car, Truck, Driller and PowerGenerator can all share the same interface IExhaust.
Short: Abstract classes are used for Modelling a class hierarchy of similar looking classes (For example Animal can be abstract class and Human , Lion, Tiger can be concrete derived classes)
AND
Interface is used for Communication between 2 similar / non similar classes which does not care about type of the class implementing Interface(e.g. Height can be interface property and it can be implemented by Human , Building , Tree. It does not matter if you can eat , you can swim you can die or anything.. it matters only a thing that you need to have Height (implementation in you class) ).
There are a couple of other differences -
Interfaces can't have any concrete implementations. Abstract base classes can. This allows you to provide concrete implementations there. This can allow an abstract base class to actually provide a more rigorous contract, wheras an interface really only describes how a class is used. (The abstract base class can have non-virtual members defining the behavior, which gives more control to the base class author.)
More than one interface can be implemented on a class. A class can only derive from a single abstract base class. This allows for polymorphic hierarchy using interfaces, but not abstract base classes. This also allows for a pseudo-multi-inheritance using interfaces.
Abstract base classes can be modified in v2+ without breaking the API. Changes to interfaces are breaking changes.
[C#/.NET Specific] Interfaces, unlike abstract base classes, can be applied to value types (structs). Structs cannot inherit from abstract base classes. This allows behavioral contracts/usage guidelines to be applied on value types.
Inheritance
Consider a car and a bus. They are two different vehicles. But still, they share some common properties like they have a steering, brakes, gears, engine etc.
So with the inheritance concept, this can be represented as following ...
public class Vehicle {
private Driver driver;
private Seat[] seatArray; //In java and most of the Object Oriented Programming(OOP) languages, square brackets are used to denote arrays(Collections).
//You can define as many properties as you want here ...
}
Now a Bicycle ...
public class Bicycle extends Vehicle {
//You define properties which are unique to bicycles here ...
private Pedal pedal;
}
And a Car ...
public class Car extends Vehicle {
private Engine engine;
private Door[] doors;
}
That's all about Inheritance. We use them to classify objects into simpler Base forms and their children as we saw above.
Abstract Classes
Abstract classes are incomplete objects. To understand it further, let's consider the vehicle analogy once again.
A vehicle can be driven. Right? But different vehicles are driven in different ways ... For example, You cannot drive a car just as you drive a Bicycle.
So how to represent the drive function of a vehicle? It is harder to check what type of vehicle it is and drive it with its own function; you would have to change the Driver class again and again when adding a new type of vehicle.
Here comes the role of abstract classes and methods. You can define the drive method as abstract to tell that every inheriting children must implement this function.
So if you modify the vehicle class ...
//......Code of Vehicle Class
abstract public void drive();
//.....Code continues
The Bicycle and Car must also specify how to drive it. Otherwise, the code won't compile and an error is thrown.
In short.. an abstract class is a partially incomplete class with some incomplete functions, which the inheriting children must specify their own.
Interfaces
Interfaces are totally incomplete. They do not have any properties. They just indicate that the inheriting children are capable of doing something ...
Suppose you have different types of mobile phones with you. Each of them has different ways to do different functions; Ex: call a person. The maker of the phone specifies how to do it. Here the mobile phones can dial a number - that is, it is dial-able. Let's represent this as an interface.
public interface Dialable {
public void dial(Number n);
}
Here the maker of the Dialable defines how to dial a number. You just need to give it a number to dial.
// Makers define how exactly dialable work inside.
Dialable PHONE1 = new Dialable() {
public void dial(Number n) {
//Do the phone1's own way to dial a number
}
}
Dialable PHONE2 = new Dialable() {
public void dial(Number n) {
//Do the phone2's own way to dial a number
}
}
//Suppose there is a function written by someone else, which expects a Dialable
......
public static void main(String[] args) {
Dialable myDialable = SomeLibrary.PHONE1;
SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....
Hereby using interfaces instead of abstract classes, the writer of the function which uses a Dialable need not worry about its properties. Ex: Does it have a touch-screen or dial pad, Is it a fixed landline phone or mobile phone. You just need to know if it is dialable; does it inherit(or implement) the Dialable interface.
And more importantly, if someday you switch the Dialable with a different one
......
public static void main(String[] args) {
Dialable myDialable = SomeLibrary.PHONE2; // <-- changed from PHONE1 to PHONE2
SomeOtherLibrary.doSomethingUsingADialable(myDialable);
}
.....
You can be sure that the code still works perfectly because the function which uses the dialable does not (and cannot) depend on the details other than those specified in the Dialable interface. They both implement a Dialable interface and that's the only thing the function cares about.
Interfaces are commonly used by developers to ensure interoperability(use interchangeably) between objects, as far as they share a common function (just like you may change to a landline or mobile phone, as far as you just need to dial a number). In short, interfaces are a much simpler version of abstract classes, without any properties.
Also, note that you may implement(inherit) as many interfaces as you want but you may only extend(inherit) a single parent class.
More Info
Abstract classes vs Interfaces
If you consider java as OOP language to answer this question, Java 8 release causes some of the content in above answers as obsolete. Now java interface can have default methods with concrete implementation.
Oracle website provides key differences between interface and abstract class.
Consider using abstract classes if :
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.
Consider using interfaces if :
You expect that unrelated classes would implement your interface. For example,many unrelated objects can implement Serializable interface.
You want to specify the behaviour of a particular data type, but not concerned about who implements its behaviour.
You want to take advantage of multiple inheritance of type.
In simple terms, I would like to use
interface: To implement a contract by multiple unrelated objects
abstract class: To implement the same or different behaviour among multiple related objects
Have a look at code example to understand things in clear way : How should I have explained the difference between an Interface and an Abstract class?
The interviewers are barking up an odd tree. For languages like C# and Java, there is a difference, but in other languages like C++ there is not. OO theory doesn't differentiate the two, merely the syntax of language.
An abstract class is a class with both implementation and interface (pure virtual methods) that will be inherited. Interfaces generally do not have any implementation but only pure virtual functions.
In C# or Java an abstract class without any implementation differs from an interface only in the syntax used to inherit from it and the fact you can only inherit from one.
By implementing interfaces you are achieving composition ("has-a" relationships) instead of inheritance ("is-a" relationships). That is an important principle to remember when it comes to things like design patterns where you need to use interfaces to achieve a composition of behaviors instead of an inheritance.
These answers are all too long.
Interfaces are for defining behaviors.
Abstract classes are for defining a thing itself, including its behaviors. That's why we sometimes create an abstract class with some extra properties inheriting an interface.
This also explains why Java only supports single inheritance for classes but puts no restriction on interfaces. Because a concrete object can not be different things, but it can have different behaviors.
Conceptually speaking, keeping the language specific implementation, rules, benefits and achieving any programming goal by using anyone or both, can or cant have code/data/property, blah blah, single or multiple inheritances, all aside
1- Abstract (or pure abstract) Class is meant to implement hierarchy. If your business objects look somewhat structurally similar, representing a parent-child (hierarchy) kind of relationship only then inheritance/Abstract classes will be used. If your business model does not have a hierarchy then inheritance should not be used (here I am not talking about programming logic e.g. some design patterns require inheritance). Conceptually, abstract class is a method to implement hierarchy of a business model in OOP, it has nothing to do with Interfaces, actually comparing Abstract class with Interface is meaningless because both are conceptually totally different things, it is asked in interviews just to check the concepts because it looks both provide somewhat same functionality when implementation is concerned and we programmers usually emphasize more on coding. [Keep this in mind as well that Abstraction is different than Abstract Class].
2- an Interface is a contract, a complete business functionality represented by one or more set of functions. That is why it is implemented and not inherited. A business object (part of a hierarchy or not) can have any number of complete business functionality. It has nothing to do with abstract classes means inheritance in general. For example, a human can RUN, an elephant can RUN, a bird can RUN, and so on, all these objects of different hierarchy would implement the RUN interface or EAT or SPEAK interface. Don't go into implementation as you might implement it as having abstract classes for each type implementing these interfaces. An object of any hierarchy can have a functionality(interface) which has nothing to do with its hierarchy.
I believe, Interfaces were not invented to achieve multiple inheritances or to expose public behavior, and similarly, pure abstract classes are not to overrule interfaces but Interface is a functionality that an object can do (via functions of that interface) and Abstract Class represents a parent of a hierarchy to produce children having core structure (property+functionality) of the parent
When you are asked about the difference, it is actually conceptual difference not the difference in language-specific implementation unless asked explicitly.
I believe, both interviewers were expecting one line straightforward difference between these two and when you failed they tried to drove you towards this difference by implementing ONE as the OTHER
What if you had an Abstract class with only abstract methods?
i will explain Depth Details of interface and Abstract class.if you know overview about interface and abstract class, then first question arrive in your mind when we should use Interface and when we should use Abstract class.
So please check below explanation of Interface and Abstract class.
When we should use Interface?
if you don't know about implementation just we have requirement specification then we go with Interface
When we should use Abstract Class?
if you know implementation but not completely (partially implementation) then we go with Abstract class.
Interface
every method by default public abstract means interface is 100% pure abstract.
Abstract
can have Concrete method and Abstract method, what is Concrete method, which have implementation in Abstract class,
An abstract class is a class that is declared abstract—it may or may not include abstract methods.
Interface
We cannot declared interface as a private, protected
Q. Why we are not declaring Interface a private and protected?
Because by default interface method is public abstract so and so that reason that we are not declaring the interface as private and protected.
Interface method
also we cannot declared interface as private,protected,final,static,synchronized,native.....
i will give the reason:
why we are not declaring synchronized method because we cannot create object of interface and synchronize are work on object so and son reason that we are not declaring the synchronized method
Transient concept are also not applicable because transient work with synchronized.
Abstract
we are happily use with public,private final static.... means no restriction are applicable in abstract.
Interface
Variables are declared in Interface as a by default public static final so we are also not declared variable as a private, protected.
Volatile modifier is also not applicable in interface because interface variable is by default public static final and final variable you cannot change the value once it assign the value into variable and once you declared variable into interface you must to assign the variable.
And volatile variable is keep on changes so it is opp. to final that is reason we are not use volatile variable in interface.
Abstract
Abstract variable no need to declared public static final.
i hope this article is useful.
For .Net,
Your answer to The second interviewer is also the answer to the first one... Abstract classes can have implementation, AND state, interfaces cannot...
EDIT: On another note, I wouldn't even use the phrase 'subclass' (or the 'inheritance' phrase) to describe classes that are 'defined to implement' an interface. To me, an interface is a definition of a contract that a class must conform to if it has been defined to 'implement' that interface. It does not inherit anything... You have to add everything yourself, explicitly.
Interface : should be used if you want to imply a rule on the components which may or may not be
related to each other
Pros:
Allows multiple inheritance
Provides abstraction by not exposing what exact kind of object is being used in the context
provides consistency by a specific signature of the contract
Cons:
Must implement all the contracts defined
Cannot have variables or delegates
Once defined cannot be changed without breaking all the classes
Abstract Class : should be used where you want to have some basic or default behaviour or implementation for components related to each other
Pros:
Faster than interface
Has flexibility in the implementation (you can implement it fully or partially)
Can be easily changed without breaking the derived classes
Cons:
Cannot be instantiated
Does not support multiple inheritance
I think they didn't like your response because you gave the technical differences instead of design ones. The question is like a troll question for me. In fact, interfaces and abstract classes have a completely different nature so you cannot really compare them. I will give you my vision of what is the role of an interface and what is the role of an abstract class.
interface: is used to ensure a contract and make a low coupling between classes in order to have a more maintainable, scalable and testable application.
abstract class: is only used to factorize some code between classes of the same responsability. Note that this is the main reason why multiple-inheritance is a bad thing in OOP, because a class shouldn't handle many responsabilities (use composition instead).
So interfaces have a real architectural role whereas abstract classes are almost only a detail of implementation (if you use it correctly of course).
Interface:
We do not implement (or define) methods, we do that in derived classes.
We do not declare member variables in interfaces.
Interfaces express the HAS-A relationship. That means they are a mask of objects.
Abstract class:
We can declare and define methods in abstract class.
We hide constructors of it. That means there is no object created from it directly.
Abstract class can hold member variables.
Derived classes inherit to abstract class that mean objects from derived classes are not masked, it inherit to abstract class. The relationship in this case is IS-A.
This is my opinion.
After all that, the interviewer came up with the question "What if you had an
Abstract class with only abstract methods? How would that be different
from an interface?"
Docs clearly say that if an abstract class contains only abstract method declarations, it should be declared as an interface instead.
An another interviewer asked me what if you had a Public variable inside
the interface, how would that be different than in Abstract Class?
Variables in Interfaces are by default public static and final. Question could be framed like what if all variables in abstract class are public? Well they can still be non static and non final unlike the variables in interfaces.
Finally I would add one more point to those mentioned above - abstract classes are still classes and fall in a single inheritance tree whereas interfaces can be present in multiple inheritance.
Copied from CLR via C# by Jeffrey Richter...
I often hear the question, “Should I design a base type or an interface?” The answer isn’t always clearcut.
Here are some guidelines that might help you:
■■ IS-A vs. CAN-DO relationship A type can inherit only one implementation. If the derived
type can’t claim an IS-A relationship with the base type, don’t use a base type; use an interface.
Interfaces imply a CAN-DO relationship. If the CAN-DO functionality appears to belong
with various object types, use an interface. For example, a type can convert instances of itself
to another type (IConvertible), a type can serialize an instance of itself (ISerializable),
etc. Note that value types must be derived from System.ValueType, and therefore, they cannot
be derived from an arbitrary base class. In this case, you must use a CAN-DO relationship
and define an interface.
■■ Ease of use It’s generally easier for you as a developer to define a new type derived from a
base type than to implement all of the methods of an interface. The base type can provide a
lot of functionality, so the derived type probably needs only relatively small modifications to its behavior. If you supply an interface, the new type must implement all of the members.
■■ Consistent implementation No matter how well an interface contract is documented, it’s
very unlikely that everyone will implement the contract 100 percent correctly. In fact, COM
suffers from this very problem, which is why some COM objects work correctly only with
Microsoft
Word or with Windows Internet Explorer. By providing a base type with a good
default implementation, you start off using a type that works and is well tested; you can then
modify parts that need modification.
■■ Versioning If you add a method to the base type, the derived type inherits the new method,
you start off using a type that works, and the user’s source code doesn’t even have to be recompiled.
Adding a new member to an interface forces the inheritor of the interface to change
its source code and recompile.
tl;dr; When you see “Is A” relationship use inheritance/abstract class. when you see “has a” relationship create member variables. When you see “relies on external provider” implement (not inherit) an interface.
Interview Question: What is the difference between an interface and an abstract class? And how do you decide when to use what? I mostly get one or all of the below answers: Answer 1: You cannot create an object of abstract class and interfaces.
ZK (That’s my initials): You cannot create an object of either. So this is not a difference. This is a similarity between an interface and an abstract class. Counter Question: Why can’t you create an object of abstract class or interface?
Answer 2: Abstract classes can have a function body as partial/default implementation.
ZK: Counter Question: So if I change it to a pure abstract class, marking all the virtual functions as abstract and provide no default implementation for any virtual function. Would that make abstract classes and interfaces the same? And could they be used interchangeably after that?
Answer 3: Interfaces allow multi-inheritance and abstract classes don’t.
ZK: Counter Question: Do you really inherit from an interface? or do you just implement an interface and, inherit from an abstract class? What’s the difference between implementing and inheriting? These counter questions throw candidates off and make most scratch their heads or just pass to the next question. That makes me think people need help with these basic building blocks of Object-Oriented Programming. The answer to the original question and all the counter questions is found in the English language and the UML. You must know at least below to understand these two constructs better.
Common Noun: A common noun is a name given “in common” to things of the same class or kind. For e.g. fruits, animals, city, car etc.
Proper Noun: A proper noun is the name of an object, place or thing. Apple, Cat, New York, Honda Accord etc.
Car is a Common Noun. And Honda Accord is a Proper Noun, and probably a Composit Proper noun, a proper noun made using two nouns.
Coming to the UML Part. You should be familiar with below relationships:
Is A
Has A
Uses
Let’s consider the below two sentences. - HondaAccord Is A Car? - HondaAccord Has A Car?
Which one sounds correct? Plain English and comprehension. HondaAccord and Cars share an “Is A” relationship. Honda accord doesn’t have a car in it. It “is a” car. Honda Accord “has a” music player in it.
When two entities share the “Is A” relationship it’s a better candidate for inheritance. And Has a relationship is a better candidate for creating member variables. With this established our code looks like this:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car
{
MusicPlayer musicPlayer;
}
Now Honda doesn't manufacture music players. Or at least it’s not their main business.
So they reach out to other companies and sign a contract. If you receive power here and the output signal on these two wires it’ll play just fine on these speakers.
This makes Music Player a perfect candidate for an interface. You don’t care who provides support for it as long as the connections work just fine.
You can replace the MusicPlayer of LG with Sony or the other way. And it won’t change a thing in Honda Accord.
Why can’t you create an object of abstract classes?
Because you can’t walk into a showroom and say give me a car. You’ll have to provide a proper noun. What car? Probably a honda accord. And that’s when a sales agent could get you something.
Why can’t you create an object of an interface? Because you can’t walk into a showroom and say give me a contract of music player. It won’t help. Interfaces sit between consumers and providers just to facilitate an agreement. What will you do with a copy of the agreement? It won’t play music.
Why do interfaces allow multiple inheritance?
Interfaces are not inherited. Interfaces are implemented. The interface is a candidate for interaction with the external world. Honda Accord has an interface for refueling. It has interfaces for inflating tires. And the same hose that is used to inflate a football. So the new code will look like below:
abstract class Car
{
string color;
int speed;
}
class HondaAccord : Car, IInflateAir, IRefueling
{
MusicPlayer musicPlayer;
}
And the English will read like this “Honda Accord is a Car that supports inflating tire and refueling”.
An interface defines a contract for a service or set of services. They provide polymorphism in a horizontal manner in that two completely unrelated classes can implement the same interface but be used interchangeably as a parameter of the type of interface they implement, as both classes have promised to satisfy the set of services defined by the interface. Interfaces provide no implementation details.
An abstract class defines a base structure for its sublcasses, and optionally partial implementation. Abstract classes provide polymorphism in a vertical, but directional manner, in that any class that inherits the abstract class can be treated as an instance of that abstract class but not the other way around. Abstract classes can and often do contain implementation details, but cannot be instantiated on their own- only their subclasses can be "newed up".
C# does allow for interface inheritance as well, mind you.
Most answers focus on the technical difference between Abstract Class and Interface, but since technically, an interface is basically a kind of abstract class (one without any data or implementation), I think the conceptual difference is far more interesting, and that might be what the interviewers are after.
An Interface is an agreement. It specifies: "this is how we're going to talk to each other". It can't have any implementation because it's not supposed to have any implementation. It's a contract. It's like the .h header files in C.
An Abstract Class is an incomplete implementation. A class may or may not implement an interface, and an abstract class doesn't have to implement it completely. An abstract class without any implementation is kind of useless, but totally legal.
Basically any class, abstract or not, is about what it is, whereas an interface is about how you use it. For example: Animal might be an abstract class implementing some basic metabolic functions, and specifying abstract methods for breathing and locomotion without giving an implementation, because it has no idea whether it should breathe through gills or lungs, and whether it flies, swims, walks or crawls. Mount, on the other hand, might be an Interface, which specifies that you can ride the animal, without knowing what kind of animal it is (or whether it's an animal at all!).
The fact that behind the scenes, an interface is basically an abstract class with only abstract methods, doesn't matter. Conceptually, they fill totally different roles.
Interfaces are light weight way to enforce a particular behavior. That is one way to think of.
As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface and Abstract class.
Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.
The below class acts as a base class for all the cars:
public class Cars
{
public string DigitalFuelMeter()
{
return "I have DigitalFuelMeter";
}
public string AirCondition()
{
return "I have AC";
}
public string SeatAdjust()
{
return "I can Adjust seat";
}
}
Consider we have a separate class for each Cars.
public class Alto : Cars
{
// Have all the features of Car class
}
public class Verna : Cars
{
// Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars
}
public class Cruze : Cars
{
// Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars
}
Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.
public abstract class Brake
{
public abstract string GetBrakeTechnology();
}
Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:
public class Verna : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars,Brake
{
public override string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.
interface IBrakeTechnology
{
string GetBrakeTechnology();
}
And the implementation is given below:
public class Verna : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use ABS system for braking";
}
}
public class Cruze : Cars, IBrakeTechnology
{
public string GetBrakeTechnology()
{
return "I use EBD system for braking";
}
}
Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.
1) An interface can be seen as a pure Abstract Class, is the same, but despite this, is not the same to implement an interface and inheriting from an abstract class. When you inherit from this pure abstract class you are defining a hierarchy -> inheritance, if you implement the interface you are not, and you can implement as many interfaces as you want, but you can only inherit from one class.
2) You can define a property in an interface, so the class that implements that interface must have that property.
For example:
public interface IVariable
{
string name {get; set;}
}
The class that implements that interface must have a property like that.
Though this question is quite old, I would like to add one other point in favor of interfaces:
Interfaces can be injected using any Dependency Injection tools where as Abstract class injection supported by very few.
From another answer of mine, mostly dealing with when to use one versus the other:
In my experience, interfaces are best
used when you have several classes
which each need to respond to the same
method or methods so that they can be
used interchangeably by other code
which will be written against those
classes' common interface. The best
use of an interface is when the
protocol is important but the
underlying logic may be different for
each class. If you would otherwise be
duplicating logic, consider abstract
classes or standard class inheritance
instead.
Interface Types vs. Abstract Base Classes
Adapted from the Pro C# 5.0 and the .NET 4.5 Framework book.
The interface type might seem very similar to an abstract base class. Recall
that when a class is marked as abstract, it may define any number of abstract members to provide a
polymorphic interface to all derived types. However, even when a class does define a set of abstract
members, it is also free to define any number of constructors, field data, nonabstract members (with
implementation), and so on. Interfaces, on the other hand, contain only abstract member definitions.
The polymorphic interface established by an abstract parent class suffers from one major limitation
in that only derived types support the members defined by the abstract parent. However, in larger
software systems, it is very common to develop multiple class hierarchies that have no common parent
beyond System.Object. Given that abstract members in an abstract base class apply only to derived
types, we have no way to configure types in different hierarchies to support the same polymorphic
interface. By way of example, assume you have defined the following abstract class:
public abstract class CloneableType
{
// Only derived types can support this
// "polymorphic interface." Classes in other
// hierarchies have no access to this abstract
// member.
public abstract object Clone();
}
Given this definition, only members that extend CloneableType are able to support the Clone()
method. If you create a new set of classes that do not extend this base class, you can’t gain this
polymorphic interface. Also, you might recall that C# does not support multiple inheritance for classes.
Therefore, if you wanted to create a MiniVan that is-a Car and is-a CloneableType, you are unable to do so:
// Nope! Multiple inheritance is not possible in C#
// for classes.
public class MiniVan : Car, CloneableType
{
}
As you would guess, interface types come to the rescue. After an interface has been defined, it can
be implemented by any class or structure, in any hierarchy, within any namespace or any assembly
(written in any .NET programming language). As you can see, interfaces are highly polymorphic.
Consider the standard .NET interface named ICloneable, defined in the System namespace. This
interface defines a single method named Clone():
public interface ICloneable
{
object Clone();
}
Answer to the second question : public variable defined in interface is static final by default while the public variable in abstract class is an instance variable.
From Coding Perspective
An Interface can replace an Abstract Class if the Abstract Class has only abstract methods. Otherwise changing Abstract class to interface means that you will be losing out on code re-usability which Inheritance provides.
From Design Perspective
Keep it as an Abstract Class if it's an "Is a" relationship and you need a subset or all of the functionality. Keep it as Interface if it's a "Should Do" relationship.
Decide what you need: just the policy enforcement, or code re-usability AND policy.
For sure it is important to understand the behavior of interface and abstract class in OOP (and how languages handle them), but I think it is also important to understand what exactly each term means. Can you imagine the if command not working exactly as the meaning of the term? Also, actually some languages are reducing, even more, the differences between an interface and an abstract... if by chance one day the two terms operate almost identically, at least you can define yourself where (and why) should any of them be used for.
If you read through some dictionaries and other fonts you may find different meanings for the same term but having some common definitions. I think these two meanings I found in this site are really, really good and suitable.
Interface:
A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively.
Abstract:
Something that concentrates in itself the essential qualities of anything more extensive or more general, or of several things; essence.
Example:
You bought a car and it needs fuel.
Your car model is XYZ, which is of genre ABC, so it is a concrete car, a specific instance of a car. A car is not a real object. In fact, it is an abstract set of standards (qualities) to create a specific object. In short, Car is an abstract class, it is "something that concentrates in itself the essential qualities of anything more extensive or more general".
The only fuel that matches the car manual specification should be used to fill up the car tank. In reality, there is nothing to restrict you to put any fuel but the engine will work properly only with the specified fuel, so it is better to follow its requirements. The requirements say that it accepts, as other cars of the same genre ABC, a standard set of fuel.
In an Object Oriented view, fuel for genre ABC should not be declared as a class because there is no concrete fuel for a specific genre of car out there. Although your car could accept an abstract class Fuel or VehicularFuel, you must remember that your only some of the existing vehicular fuel meet the specification, those that implement the requirements in your car manual. In short, they should implement the interface ABCGenreFuel, which "... enables separate and sometimes incompatible elements to coordinate effectively".
Addendum
In addition, I think you should keep in mind the meaning of the term class, which is (from the same site previously mentioned):
Class:
A number of persons or things regarded as forming a group by reason of common attributes, characteristics, qualities, or traits; kind;
This way, a class (or abstract class) should not represent only common attributes (like an interface), but some kind of group with common attributes. An interface doesn't need to represent a kind. It must represent common attributes. This way, I think classes and abstract classes may be used to represent things that should not change its aspects often, like a human being a Mammal, because it represents some kinds. Kinds should not change themselves that often.

Achieving multiple inheritance via interface

I am a beginner in interface concept.
when I surfing for the information about "Achieving multiple inheritance via interface", I came across this link.. Multiple inheritance
I have a same doubt as the programstudent had.
hi, Good Explanation very much helpful In the uml diagram for java
there is no connection to Animal from Bird and horse why? Is it
necessary to use the implement the same method in the derived class
and why
void birdNoise();
void horseNoise();
why in the Peagus class
public void horseNoise()
{
System.out.println("Horse Noise!");
}
public void birdNoise()
{
System.out.println("Bird Noise!");
}
why this must be there? Why "Remember, we must write each class's own implementation for each method in the interface. reason? Thank for this good explanation Thank you
In that post, they have used multiple inheritance in c++ and converted to interfaces in java.
1.what I thought about inheritance is having some methods in parent class, and whenever the same methods are needed in other class(es) too, then those class(es) will inherit the parent class and use it.
But in interface concept if each derived class(es) has to define its own implementation then what is the use of inheriting it?
2.If we have to provide own implementation then why not we define that method in the derived class(es) itself. What is the use of inheriting it?
Someone please explain.
Thanks in advance.
When I switched from c++ to java I had this same feeling but now that I been working with java for a while it all kinda makes sense.
1.what I thought about inheritance is having some methods in parent
class, and whenever the same methods are needed in other class(es)
too, then those class(es) will inherit the parent class and use it.
Like the original author did, you can still do multiple inheritance in java you just must use interfaces. Interfaces are like pure virtual classes in c++.
But in interface concept if each derived class(es) has to define its
own implementation then what is the use of inheriting it?
The reason you implement an interface in java is so that you guarantee that class has those methods. That way you can have a specific class implement a generic interface and then treat every specific class that implements that generic interface the same.
Java Design is a bit different then c++ design but after doing several java program's you will become just as good at using multiple interfaces as you are at using multiple inheritance.
Each subclass has to define it's own implementation because each subclass may perform the operation slightly differently. Consider the following example:
public interface animal {
//All implementers must define this method
void speak();
}
This interface states that any Animal MUST have a way to speak. Basically, any type of animal is going to be able to make a noise. We then have 2 subclass, or 2 different types of animals that we create.
public class Dog implements animal {
//Define how a Dog speaks
public void speak() {
System.out.println( "woof" );
}
}
We then define another animal, cat
public class Cat implements animal {
//Define how a Cat speaks
public void speak() {
System.out.println( "meow" );
}
}
In this example, both Cat and Dog are animals, and therefore must be able to speak due to our interface. However, everybody knows that cats and dogs make different sounds. By allowing each subclass to define how it 'speaks', we can give Dog and Cat their own respective sound when the speak() method is called, while ensuring they are both Animals.
In answer to your question more specifically, inheritance forces it's subclasses to have a specific method. In other words, an interface states that "all my subclasses will define each of these methods". What this allows us to do is to write code that deals with the methods in an interface without knowing the specific subclass. We can safely do that because we know that each subclass MUST have defined the method in the interface class. If only the subclasses that use the method defined it, then we would have no way of knowing for sure whether it is safe to call the method on all subclasses.
Just a note: If you do not want a subclass to define the method, you can simply define an empty method like this:
public class MuteAnimal implements animal {
//A MuteAnimal can't speak!
public void speak() { }
}
Inheritance is often useless without polymorphism. It is really not easy to explain it all just in few sentences. My advices would be to look at interfaces for defining behavior (something like can-do relationship), and concrete inheritence for is-a relationships.
In the center of everything as you may learn is something called Single Responsibility Principle. This means that one class has one responsibility, if you are having more of them, you separate the class.
If you take your example, even the Pegasus isn't both horse and bird at the same time 100% percent. It would inherit the horse, but implement specific characteristics of the birds, which would be defined in interfaces, like Flyable for instance. You can say that birds have one way of flying common to them all, so inherit them from Bird. Pegasus is a little different, so that custom logic can be defined after you implement the Flyable interface with method Fly.
Also, the example with horseNoise and birdNoise is little unrealistic, you want one method speak() which will due to internal class alhorithm perform certain action. What if that pegasus could talk? Would you have a method for each word?
Back to Flyable example, say you now have a video-game. Now you can have polimorphism for this: Lets say that in game earthquake happens. You want for each animal that can fly to go and fly. You have a collection of animals currently in game, so you write this:
foreach(Flyable flyableAnimal in animals)
flyableAnimal.Fly();
You just rely on polimorphism ...
These were just some random thoughts, you can find far better examples online, hope this helps ...
If class A inherits from class B, that effectively means two things:
Class A can implicitly use all methods and properties of class B, and need only define that functionality which is in fact unique to class A.
Code which expects an object of type B will accept an object of type A.
Those two features of inheritance are in some sense orthogonal; one can imagine places where either could be useful without the other. Although derived classes can only have one parent class from which they gain implicit access to methods and properties, they may define an arbitrary number of interfaces for which they are substitutable.
Note that while some people insist that interfaces form a "has-a" rather than "is-a" relationship, I think it's better to think of them as saying something "is __able" or "is a __er", the point being that interfaces don't just define abilities, but define substitutability (i.e. "is a") in terms of ability.

what is the advantage of interface over abstract classes?

In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.
I believe overriding methods in subclasses/implementations is possible in both cases, therefore, what is the real advantage of one over the other (interfaces vs abstract classes in Java)?
Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."
Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."
Abstract classes have some serious drawbacks. For example:
class House {
}
class Boat {
}
class HouseBoat extends /* Uh oh!! */ {
// don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}
You can get through via an interface:
interface Liveable {
}
interface Floatable {
}
class HouseBoat implements Liveable, Floatable {
}
Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)
And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.
Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).
Abstract classes are useful when you need concrete behaviour from the base class.
The facts are-
Java doesn't support multiple inheritance
Multiple interfaces can be implemented
Few methods in an abstract class may be implemented
These facts can be used to tilt the advantage in favor of interfaces or abstract classes.
If there are more than one behavior that a class must share with other classes, interfaces win.
If a method definition has to be shared/ overridden with other classes, abstract classes win.
An class may implement several interfaces, whereas it may only extend one class (abstract or concrete), because Java does not support multiple inheritance.
In OOP (mostly independent of a concrete language) abstract classes are a re-use mechanism for the class hierarchy for behaviour and structure which isn't complete on its own.
Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation.
All other differences are technical details, important is different usage.
You dont override an interface. You implement it.
Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.
Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.
-Method without any implementation is abstract method,whenever a class contains one or more abstract method,then it must be declared as a abstract class
-Interface is fully abstract which cannot have constructor,instance and static blocks,and it contains only two types of members
1.public abstract method
2.public-static-final variable
*Both cannot be instantiated but reference can be created.
*Which one suits better depends on the application
-Interfaces are useful because Java classes will not support multiple inheritance but interfaces do.
-Abstract classes are useful when you need concrete behavior from the base class.
The main advantages of interface over abstract class is to overcome the occurrence of diamond
problem and achieve multiple inheritance.
In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java.
So to achieve multiple inheritance we use interface .
class Animal
{ void move(){} }
class Bird
{ void move(){fly} }
class Fish
{ void move(){swim} }
Now, if class Animal is abstract class like
Animal a;
a= new Bird(); or a = new Fish()
Here, abstraction works well, but if there are 100 objects like Animal a[100];
You can not write new Bird().move or new Fish().move 100 times
Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked
Second it supports multiple inheritance as class A can implements as many interfaces.
Amazing answers!!
I too want to put my opinion on Interface.
As the name says it is interface which means it will provide interface between two classes.
It help a class or interface hold multiple behavior at the same time.
Who ever having the interface can access the behavior of the class agreed with the interface.
interface teacher
{
//methods related to teacher
}
interface student
{
//methods related to student
}
interface employee
{
//methods related to employee
}
class Person:teacher,student,employee
{
//definition of all the methods in teacher,student, employee interface
//and method for person
}
Now here which ever class is having teacher interface will have access to only teacher behavior of Person.
Similarly the class or module having student interface will have access to only student behavior of person.
Using abstract class, it is not at all possible.
Hope this will add some additional points. :)
Happy coding!!.

Categories