what is the actual use of interface in java? [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Abstract class and Interface class?
Java: interface / abstract classes / abstract method
In Java, whatever use of interface is fulfilled by abstract class. I know one advantage of interfaces is that if we implement an interface then we can also extend another class. Is there any other use or advantage of interface in Java?

Interfaces allow you to use classes in different hierarchies, polymorphically.
For example, say you have the following interface:
public interface Movable {
void move();
}
Any number of classes, across class hierarchies could implement Movable in their own specific way, yet still be used by some caller in a uniform way.
So if you have the following two classes:
public class Car extends Vehicle implements Movable {
public void move() {
//implement move, vroom, vroom!
}
}
public class Horse extends Animal implements Movable {
public void move() {
//implement move, neigh!
}
}
From the perspective of the caller, it's just a Movable
Movable movable = ...;
movable.move(); //who am I?
I hope this helps.

What you like : thousands of abstract methods in one Abstract Class and inherit this class OR make as many interfaces for specific abstract methods and use those only you want by inheriting as many interfaces as needed...
abstract class A
{
//thousands of abstract method();
abstract methodA();
abstract methodB();
abstract methodC();
}
//OR
interface ForOnlymethodA
{
void methodA();
}
interface FormethodBandmethodC
{
void methodB();
void methodC();
}
So, use that method only what you just need by inheriting particular interface, if you are inheriting Abstract classes then you are unnecessarily inheriting all methods that you don't need in one class and may be needed in some other classes..

Multiple interfaces can be implemented, but only one class can be extended. A completely abstract class is a lot like an interface, except that an abstract class can contain variables.
It really depends on what you need. C++ allows you to extend as many classes you want, and it turns into a bit of a disaster. The nice thing about having only one superclass is that there's only ever one other set of implementations that you have to worry about (even if the parent has a parent, the parent's particular combination becomes your parent...)
Interfaces allow one object to play many roles, but they don't allow code reuse.
It's really to simplify thinking about inheritance. On the balance, I think they got it right.

Advantages over an abstract class? except the fact you can implement multiple interfaces but extend only one (abstract or not) class, it's the same as an abstract class that all of it's methods are abstract and public

Interfaces allow the nominative typing in Java to work across disjoint class hierarchies.
This is due to the "single inheritance" limitation on a class hierarchy and "closed types". I will hold my tongue on subtype polymorphism and Java's implementation of it ;-)
There are other solutions to this problem such as dynamic typing, structural typing, multiple inheritance, and traits, etc. Each approach has advantages and dis-advantages. Interfaces were just the approach that Java took.

Java interface
- provides the data encapsulation which means, implementation of the methods can not be seen. The class which extends this interface must implement all the methods declared in it.
more info: wiki answer

Related

Technical difference between abstract class and interface [duplicate]

This question already has answers here:
What is the difference between an interface and abstract class?
(38 answers)
Closed 8 years ago.
Conceptually I know the difference between abstract class and interface. But wondering about the technical difference between these two. Why Sun made this interface term even though I can have fully abstract class and make my work done.
Read here http://javarevisited.blogspot.kr/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html
Difference between abstract class and interface in Java
Abstract Class vs Interface in Java and When to use them over otherWhile deciding when to use interface and abstract class, it’s important to know difference between abstract class and interface in Java. In my opinion, following two differences between them drives decision about when to use abstract class or interface in Java.
1) Interface in Java can only contains declaration. You can not declare any concrete methods inside interface. On the other hand abstract class may contain both abstract and concrete methods, which makes abstract class an ideal place to provide common or default functionality. I suggest reading my post 10 things to know about interface in Java to know more about interfaces, particularly in Java programming language.
2) Java interface can extend multiple interface also Java class can implement multiple interfaces, Which means interface can provide more polymorphism support than abstract class . By extending abstract class, a class can only participate in one Type hierarchy but by using interface it can be part of multiple type hierarchies. E.g. a class can be Runnable and Displayable at same time. One example I can remember of this is writing GUI application in J2ME, where class extends Canvas and implements CommandListener to provide both graphic and event-handling functionality..
3) In order to implement interface in Java, until your class is abstract, you need to provide implementation of all methods, which is very painful. On the other hand abstract class may help you in this case by providing default implementation. Because of this reason, I prefer to have minimum methods in interface, starting from just one, I don't like idea of marker interface, once annotation is introduced in Java 5. If you look JDK or any framework like Spring, which I does to understand OOPS and design patter better, you will find that most of interface contains only one or two methods e.g. Runnable, Callable, ActionListener etc.
I haven't included all syntactical difference between abstract class and interface in Java here, because focus here to learn when to use abstract class and interface and choosing one over other. Nevertheless you can see difference between interface and abstract class to find all those syntactical differences.
Read more: http://javarevisited.blogspot.com/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html#ixzz31l59K92Z
you are free to choose interface or abstract class in the above scenario
but keep below things in mind
if you made a fully abstract class then
your subclass will extend one class to implement that behaviour and
its not eligible to extend any other class as multiple inheritance is not supported in java.
see without interface we cant achieve multiple inheritance.
Now if we approach interface instead of fully abstract class
then class can implement it and still eligable for extension of one more class.
so choose fully abstract class in your design if your sub classes can never need to extend any other class.
if sub classes need to extend some classes later (usually its how we need in application) then choose interface.
You write a java program with interfaces, abstract class and concrete class but do not mention any constructor, compile it and see byte codes in .class files. You would see as expected abstract class and concrete classes have default constructor added by compiler where as interfaces do not get constructor added to it by compiler. This should help you understand technical differences as I believe you know other differences.
I might receive downvotes for this answer :) . Consider this scenario.
public class TestClass{
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Fish f = new Fish();
f.walk();
}
}
abstract class Animal {
protected void walk() {
System.out.println("walking");
}
}
class Fish extends Animal {
}
O/ P : walking
Technically a fish can't walk. Still since it extends the Animal class, it "can" walk which is wrong from a design perspective(even though Fish doesn't implement walk(), it can still call it).. If Animal were to be an Interface, then Fish must implement the method walk() which it won't / shouldn't. So, you will be forced to relook at the design.
Because you can have a class implement 2 interfaces, but you can't have a class implement (or extend) 2 abstract classes.
An abstract class can have some implementation code and instance variables. An interface has only method signatures and static variable definitions, no implementation code.
Further, if you implement an interface you must include implementation code for all of the methods defined in the interface.

Difference between abstract class with all method abstract and interface?

I had an interview where interviewer asked me first what is the difference between abstract class with all the methods abstract and an interface.
I replied that if it is required to inherit something in the future you will not be able to do it if you have already extended a class.
Then, he stated that it was a situation where one would never have to extend any other class and you have to implement a contract. In this circumstance, which would be better, an abstract class or an interface?
I told him you can use either of them but he was not satisfied. I could not understand why - I believe that is a developer/design choice.
The answer stating that an interface represents a contract is not acceptable.
That's the answer we give to Junior since it may be too complex to clearly figure out the difference between the essence of an abstract class and the essence of an interface without much architecture experience and without reading a lot of classic books about.
Any abstract class with public methods acts as a contract, as well as an interface.
An abstract class that doesn't provide any implementation is in 99% of cases a representation of an object's Role.
An interface represents a Role.
Each object might have several different roles that shouldn't be tied together but composed by the concerned object.
I'm explaining this with this example:
Your interviewer could say:
I have a Robot that can walk and a Human that can walk too.
So based on this case, he asks you: should I extract the walking feature in an abstract base class or in an interface, knowing that the implementations have nothing in common?
You think..."oh I know so: in this case, having one abstract class with an abstract method walk(), then is clearly the same than declaring an interface with the walk() method."
So your answer would surely be: "it's the choice of the developer !".
And it's really not an always valid answer.
Why? Let's see the next expectation:
A Human can eat, but obviously the Robot cannot and even doesn't need.
What if you implemented the walking feature with an abstract class? You would end up with:
public abstract class Biped {
public void abstract walk();
}
public Robot extends Biped {
public void walk() {
//walk at 10km/h speed
}
}
public Human extends Biped {
public void walk() {
//walk at 5km/h speed
}
}
How could you plug the eating feature? You're stuck because you can't implement it in the Biped base class since it would break Liskov Substitution Principle, since a Robot doesn't eat!
And you can't expect Human extending another base class due to the known Java rule.
Of course, you could add a specific Feedable interface only dedicated to Human:
public interface Feedable {
void eat();
}
Signature becomes: public Human extends Biped implements Feedable {
Clearly, it makes no sense and confusing to have one role implemented through a class and the other through an interface.
That's why starting with interface is really preferred whenever we have the choice.
With an interface, we can model Roles easily by composing.
So the final solution would then be:
public interface Walkable {
void abstract walk();
}
public interface Feedable {
void eat();
}
public Robot implements Walkable {
public void walk() {
//walk at 10km/h speed
}
}
public Human implements Walkable, Feedable {
public void walk() {
//walk at 5km/h speed
}
public void eat(){
//...
}
}
Doesn't it remind you the Interface Segregation Principle? ;)
To sum up, if you specify an IS-A relationship, uses an abstract class.
If you realize that you are about to model a Role (let's say a IS-CAPABLE-OF relationship), go with interface.
Here are the differences:
A class can extend exactly abstract class, but can implement any number of interfaces.
An abstract class can have protected, private (does not apply to your question), package, and public methods, but an interface can only have public methods.
An abstract class can have instance variables (often called data members or properties) while an interface can only have static variables.
The answer to the question: "blah never extend blah implement contract blah" is this: "I would use an abstract class if I did needed instance variables and/or non-public methods and otherwise I would use an interface".
Interfaces are the natural way of creating a contract because they force you to implement the methods they define.
Besides that, you can implement as many as you want in the case you want to add new interfaces to your class.
I can't say what your interviewer had in mind, but an interface is more of a "contract" whereas an abstract base class, while it can play that role too, is more geared towards hierarchies or IS-A relationships. E.g. an Apple IS-A Fruit, a Pear IS-A Fruit, etc. But you're right, they could well be used interchangeably for practical purposes in that context, but an OO purist might not want to use an abstract class unless they were expressing IS-A relationship(s).
One thing to keep in mind is be the ability to have diamond inheritance for interfaces.
Consider this interface hierarchy:
interface Base{}
interface Sub1 extends Base{}
interface Sub2 extends Base{}
interface SubSub extends Sub1, Sub2{}
The same wouldn't be possible with abstract classes:
abstract class Base{}
abstract class Sub1 extends Base{}
abstract class Sub2 extends Base{}
// NOT ALLOWED! can only extend one class
// abstract class SubSub extends Sub1, Sub2{}
This is something that would be allowed in C++ (although tricky to get right). I think he might have been fishing for this. In general, this is the ultimate reason why I always try to write interface hierarchies instead of class hierarchies.
For the first situation i'd chose interface over abstract class with all methods abstract as having interface leaves me with option in future for my implementing class to extend some other (abstract) class.
For second scenario, if you really don't want your concrete class to extend any other class and also want to "implement" contract, you can have abstract class with all methods abstract.
I can see such question was already answered. BTW, I would like to share what I consider the best explanation I have read so far.
The bellow text was copied and pasted from Deshmukh, Hanumant. OCP Oracle Certified Professional Java SE 11 Programmer I Exam Fundamentals 1Z0-815: Study guide for passing the OCP Java 11 Developer Certification Part 1 Exam 1Z0-815 (p. 319). Enthuware. Edição do Kindle.
13.2 Distinguish class inheritance from interface inheritance including abstract classes 13.2.1 Difference between Interface and Abstract Class ☝
"What is the difference between an interface and an abstract class" is usually the first question that is asked in a Java "tech-check". While being a simple ice breaker, it also an excellent question to judge a candidate's understanding of OOP. Candidates usually start parroting the technical differences such as an interface cannot have method implementations (which it can, since Java 8), while abstract class can. An interface cannot have static methods (which it can, since Java 8) or instance fields while an abstract class can and so on. All that is correct, but is not really impressive. The fundamental difference between an interface and an abstract class is that an interface defines just the behavior. An interface tells you nothing about the actual object other than how it behaves. An abstract class, on the other hand, defines an object, which in turn, drives the behavior. If you understand this concept everything else about them will fall in place. For example, "movement" is a behavior that is displayed by various kinds of objects such as a Car, a Cat, or a StockPrice. These objects have no commonality except that they move. Saying it the other way round, if you get an object that "moves", you don't get any idea about what kind of an object are you going to deal with. It could be a Car, a Cat, or a StockPrice. If you were to capture this behavior in Java, you would use an interface named Movable with a method named move(). On the other hand, if you talk about Automobile, a picture of an object starts forming in your head immediately. You can sense that an Automobile would be something that would have an engine, would have wheels, and would move. You intuitively know that a StockPrice or a Cat cannot be an Automobile even though they both do move. An abstract class is meant exactly for this purpose, when, once you identify a conceptual object, you do not need to worry about its behavior. The behavior kind of flows automatically. If you create an abstract class named Automobile, you are almost certain that it would have methods such a move, turn, accelerate, or brake. It would have fields for capturing inner details such Engine, Wheels, and Gears. You get all that just by saying the word Automobile. From the above discussion, it should be clear that interfaces and abstract classes are not interchangeable. Even though an abstract class with no non-abstract method looks functionally similar to an interface, both are fundamentally different. If you are capturing a behavior, you must use an interface. If you are capturing a conceptual object, you must use an abstract class.

Why doesn't interfaces implement methods and override them?

I already read the post of research effort required to post a SO question. I am ashamed again to post this question to a pile of million questions. But I still don't get the idea of interfaces in java. They have unimplemented methods and then defined for every class in which they are implemented. I searched about it. Interfaces were used to support multiple inheritance in java and also to avoid (Deadly) Diamond Death of inheritance. I also came across Composition vs Inheritance and that inheritance is not for code reuse and its for polymorphism. So when I have a common code as a class to extend it will not be supported due to multiple inheritance which gives the option to use Interfaces(Correct me if I am wrong). I also came across that its not possible in most cases to define a generic implementation. So what is the problem in having a common definition (not a perfect generic implementation) of the interface method and then Override it wherever necessary and why doesn't java support it. Eg. When I have 100 classes that implements an interface 70 of them have a common implementation while others have different implementation. Why do I have to define the common method in interface over 70 classes and why can't I define them in Interface and then override them in other 30 classes which saves me from using same code in 70 classes. Is my understanding of interfaces wrong?
First, an interface in Java (as of Java 7) has no code. It's a mere definition, a contract a class must fulfill.
So what is the problem in having a common definition (not a perfect
generic implementation) of the interface method and then Override it
wherever necessary and why doesn't java support it
Yes you can do that in Java, just not with interfaces only. Let's suppose I want from this Example interface to have a default implementation for method1 but leave method2 unimplemented:
interface Example {
public void method1();
public String method2(final int parameter);
}
abstract class AbstractExampleImpl implements Example {
#Override
public void method1() {
// Implement
}
}
Now classes that want to use this method1 default implementation can just extend AbstractExampleImpl. This is more flexible than implementing code in the interface because if you do so, then all classes are bound to that implementation which you might not want. This is the advantage of interfaces: being able to reference a certain behavior (contract) without having to know how the class actually implements this, for example:
List<String> aList = MyListFactory.getNewList();
MyListFactory.getNewList() can return any object implementing List, our code manipulating aList doesn't care at all because it's based on the interface.
What if the class that uses interface already is a Sub-class. Then we
can't use Abstract class as multiple inheritance is not supported
I guess you mean this situation:
class AnotherClass extends AnotherBaseClass
and you want to extend AbstractExampleImpl as well. Yes, in this case, it's not possible to make AnotherClass extend AbstractExampleImpl, but you can write a wrapped inner-class that does this, for example:
class AnotherClass extends AnotherBaseClass implements Example {
private class InnerExampleImpl extends AbstractExampleImpl {
// Here you have AbstractExampleImpl's implementation of method1
}
}
Then you can just internally make all Example methods being actually implemented by InnerExampleImpl by calling its methods.
Is it necessary to have the interface in AnotherClass?
I guess you mean AnotherClass implements Example. Well, this is what you wanted: have AnotherClass implement Example with some default implementation as well as extend another class, or I understood you wrong. Since you cannot extend more than one class, you have to implement the interface so you can do
final Example anotherClass = new AnotherClass();
Otherwise this will not be possible.
Also for every class that implements an interface do I have to design
an inner class?
No, it doesn't have to be an inner class, that was just an example. If you want multiple other classes have this default Example implementation, you can just write a separate class and wrap it inside all the classes you want.
class DefaultExampleImpl implements Example {
// Implements the methods
}
class YourClass extends YetAnotherClass implements Example {
private Example example = new DefaultClassImpl();
#Override
public void method1() {
this.example.method1();
}
#Override
public String method2(final int parameter) {
return this.example.method2(parameter);
}
}
You can create an abstract class to implement that interface, and make your those classes inherit that abstract class, that should be what you want.
A non abstract class that implements and interface needs to implement all the methods from the interface. A abstract class doesn't have to implement all the methods but cannot initiated. If you create abstract class in your example that implements all the interface methods except one. The classes that extend from these abstract class just have to implement the one not already implemented method.
The Java interfaces could have been called contracts instead to better convey their intent. The declarer promise to provide some functionality, and the using code is guaranteed that the object provides that functionality.
This is a powerful concept and is decoupled from how that functionality is provided where Java is a bit limited and you are not the first to notice that. I have personally found that it is hard to provide "perfect" implementations which just need a subclass or two to be usable in a given situation. Swing uses adapters to provide empty implementations which can then be overrides as needed and that may be the technique you are looking for.
The idea of the interface is to create a series of methods that are abstract enough to be used by different classes that implement them. The concept is based on the DRY principle (Don't repeat yourself) the interface allows you to have methods like run() that are abstract enough to be usuable for a game loop, a players ability to run,
You should understand the funda of interface first. Which is
It is use to provide tight coupling means tight encapsulation
It helps us to hide our code from the external environment i.e. from other class
Interface should have only definition and data which is constant
It provide facility to class open for extension. Hence it cannot be replace by the any other class in java otherwise that class will become close for extension. which means class will not be able to extend any other class.
I think you are struggling with the concept of Object Oriented Design more than anything. In your example above where you state you have 100 classes and 70 of them have the same method implementation (which I would be stunned by). So given an interface like this:
public interface Printable
{
void print();
}
and two classes that have the "same" implementation of print
public class First implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
public class Second implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
you would instead want to do this:
public abstract class DefaultPrinter implements Printable
{
public void print()
{
System.out.println("Hi");
}
}
now for First and Second
public class First extends DefaultPrinter
{
}
public class Second extends DefaultPrinter
{
}
Now both of these are still Printable . Now this is where it gets very important to understand how to properly design object hierarchies. If something IS NOT a DefaultPrinter YOU CANNOT AND SHOULD NOT make the new class extend DefaultPrinter

Why use abstract class and not interface?

For example a real estate builder is constructing an apartment with many flats. All the rooms in the flats have the same design, except the bedroom. The bedroom design is left for the people who would own the flats i.e; the bed Rooms can be of different designs for different flats.
I can achieve this through an abstract class like below:
public abstract class Flat
{
//some properties
public void livingRoom(){
//some code
}
public void kitchen(){
//some code
}
public abstract void bedRoom();
}
}
An implementation class would be as follows:
public class Flat101 extends Flat
{
public void bedRoom() {
System.out.println("This flat has a customized bedroom");
}
}
Alternatively I can use an interface instead of an abstract class to achieve the same purpose like follows:
class Flat
{
public void livingRoom(){
System.out.println("This flat has a living room");
}
public void kitchen(){
System.out.println("This flat has a kitchen");
}
}
interface BedRoomInterface
{
public abstract void bedRoom();
}
public class Flat101 extends Flat implements BedRoomInterface
{
public void bedRoom() {
System.out.println("This flat has a customized bedroom");
}
}
Now the question is : For this why should choose to use an interface (or) why should I choose to use an abstract class?
It depends on your intention or use case. But in general, you should prefer interface over abstract classes (Item 18 in Bloch's Effective Java). Abstract classes are more fragile, because someone may modify the abstract class changing the behavior of other classes extending from it (this is a general statement).
It's more flexible to work with interfaces, because if you have BedroomInterface and LivingRoomInterface, then you can have FlatInterface implementing both interfaces, then Flat101 implementation class implements FlatInterface (instead of extending from Flat then implementing an interface). This seems clearer, and later on you can have ExecutiveFlatInterface which not only have bedroom and living room but also guess room, then Flat102 can implement from it.
Option 2 is to have Flat101 extend from Flat, then Flat implements BedroomInterface and LivingRoomInterface. This really depends on what you want to do and what methods are likely needed.
If you're designing an API that is going to be widely used, you'd use both: an interface to express the contract to be fulfilled by implementing classes, and an abstract class which partially implements that interface and thus permits code re-use.
As an example, consider Java's List: methods in the Collections framework (eg Collections.sort()) are written in terms of the List interface, which is partially implemented by the abstract class AbstractList, which in turn is extended into the concrete implementations LinkedList and ArrayList. LinkedList and ArrayList re-use code from AbstractList, but that does not prevent someone from writing their own completely separate implementation of List and then sorting it using Collections.sort().
That said, in a lot of circumstances this approach can be overkill. If the type hierarchy you're building is only used within a relatively small scope, its generally fine to just use abstract classes. If you decide later on that you want an interface later, its a pretty painless refactoring task to change things.
Abstract classes do have a few advantages:
they allow you to specify abstract methods with package/protected modifiers
they facilitate code re-use
via the use of abstract methods and final methods on the super class they allow you to restrict the manner in which your class is subclassed, which can be useful in a wide variety of circumstances (see also: the Template pattern)
code that references classes is generally easier to follow in an IDE (clicking "open declaration" on an abstract class type parameter is usually more useful than on an interface type parameter)
If you have a class which provides some of the functionality required by derived classes, but each derived class additionally requires differing implementation of other functionality, then an abstract class provides a means of defining the common implementation, while leaving the specific behaviors required by derived classes to be made specific to each derived class.
I feel it is generalization means; an abstract class is most useful if the property and the behaviors of the class are common among a given package or module. One good example is drum brake; as all drum brake works same way holding brakes inside wheel drum so this behavior can be inherited in all class of cars which uses drum brake.
For interface; it is more like specification or contract which force you to implement its speciation. Let’s take an example of model of a building it has all speciation like doors, window, lift ….. But while you implement the model into actual building you we need to keep the window but the internal behavior is decided by (as the widow could be a simple widow or a slider window, the color and material …)
Hope this helps!!
I feel when we need to implement some common functionality and some abstract functionality for multiple class then we should use abstract class. If we see the example of Flat, where we have some common design and some custom design, in such use case it is better to use abstract rather then use interface again to implement custom function and use of abstract as derived class doesn't create an extra instance as normal derived class.
You can not extends more than one class but you can implements more than one interface
If you need to change frequently of your design then abstract class is better because any change happen in abstract class , no force implementation need in sub class. But If any change in interface you have to implement of the implementation class.

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