Technical difference between abstract class and interface [duplicate] - java

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.

Related

Add methods to classes without breaking implementations

Let say I have 2 classes called class Cow ad class Pig.
They both implements interface Animal.
For the interface there are only 2 methods called public void eat() and public void speak().
All is fine. But while this seems good making use of interfaces, I thought that if I ever needed to add method(s) to this interface, implementation would break, namely I would need to go implement the new methods in these classes, which breaks the "close-open principle".
So I thought of, in addition to interface, I would make use of abstract class as well, should it be needed that I needed to add new method(s) in the future.
So, for example, public class Cow extends ... implements Animal.
It sounds like a good plan (if it is not, please correct me).
But the problem is, what if these classes extend already some other class? In such case, I could not extend 2 classes.
So my question is:
Is there a pattern where I could declare a common interface of
related classes while withholding the ability to add new methods in
the future that doesn't break the "closed-open principle" and doesn't
break implementations?
With Java 8 there are default methods
public interface Animal {
void eat();
void speak();
default void sleep(){}
}
Now your Animal must override eat and speak but may choose to override sleep.
Pre Java 8 using a abstract class was the usual way to protect against having to implement every interface method. As you noted, this doesn't work with multiple inheritance so cannot be used to solve all cases.
P.S. don't declare interface methods public, this is the default visibility for all interface members.
In Java 8, interfaces can define default methods for this purpose.

When shall we go for interface or abstract class in Java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use an interface instead of an abstract class and vice versa?
Can any one tell me under which circumstances we should go for interface and abstract class.
Java specific aspects are welcome.
Always use an interface unless you need to ...
... provide subclasses with some state
... provide subclasses with default implementations of some methods
... want to defer implementation of some of the abstract methods
Note that you can only extend one class, while you can implement multiple interfaces. So if there's any chance that a subclass will need to extend some other class, strive for using an interface.
Here are some good links that discusses this topic:
Java World: Abstract classes vs. interfaces
Interface vs Abstract Class (general OO)
Abstract Class versus Interface
Mindprod: Interfaces vs Abstract classes
In simple Language :
Use interface if you want your objects be accessed by common way.
Use abstract class if you want to define some functionality in super class and to define prototype of some methods that must be override in child classes i.e., extending the functionality of a class.
Here is a funny example that might help you to clear the fundamentals.
http://ganeshtiwaridotcomdotnp.blogspot.com/2011/05/understanding-importance-of-interface.html
If you don't want to implement any method and you just want to define your contract, then you use an interface.
However, if you do want to have some implementation already, you should use an abstract class.
You will use an abstract class if you want to provide a partial implementation for the subclasses to extend, and an interface if you only want to provide signatures of methods that must be implemented.
It is perfectly normal to provide both and interface and an abstract class that implements parts of it.
There is however one limitation of abstract classes: In a subclass you can only extend one (abstract) class, but you may implement as many interfaces as you like in a single class.
Interfaces are simply a collection of public method signatures and public static final fields. No constructors, no protected/internal methods, no other type of fields.
On the other hand, any class can be abstract simply by putting abstract in front of its declaration. They can declare abstract methods and implement interfaces and other abstract classes without defining the method implementation.
An abstract class is more restrictive when it comes to inheritance (only one can father a subclass), but you can implement methods and constructors in it.
Any number of interfaces can be implemented by a class, but there is no default method & constructor implementation.
That is why it is always a good idea to provide an abstract class next to an interface as a default implementation option.
Check these
http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html
Abstract class and interface

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!!.

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

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

When to use extends and when to use interface?

We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.
In what cases should we be using extends?
extends is used for either extending a base class:
class ClassX extends ClassY {
...
}
or extending an interface:
interface InterfaceA extends InterfaceB {
...
}
Note that interfaces cannot implement other interfaces (most likely because they have no implementation).
Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo for interfaces in the .NET world) and instead uses the difference between extends and implements to signify the difference to the programmer:
class ClassA extends ClassB implements InterfaceC, InterfaceD {
...
}
Here you can clearly see that you're building upon an existing implementation in ClassB and also implement the methods from two interfaces.
Is a matter of uses. Interfaces can be used as a contract with your application and then base classes can be use to extend that interface, so it is loosely couple.
Take for example Injection Dependency pattern:
You first write a contract:
public interface IProductRepository
{
IList<T> GetAllProducts();
}
Then you extend your contract with a base class:
public abstract BaseProductRepository : IProductRepository
{
public IList<T> GetAllProducts()
{ //Implementation }
}
Now you have the option to extend base into two or more concrete classes:
public class InternetProductRepository extends BaseProductRepository;
public class StoreProductRepository extends BaseProductRepository;
I hope this small examples clears the differences between extend and Implement. sorry that I did not use java for the example but is all OO, so I think you will get the point.
Thanks for reading, Geo
I did not complete the code for injection dependency pattern but the idea is there, is also well documented on the net. Let me know if you have any questions.
Actually, you can extend an interface - in the case where you're defining another interface.
There are lots of quasi-religious arguments about this issue and I doubt there's a clear right answer, but for what it's worth here's my take on things. Use subclassing (i.e. extends), when your various classes provide the same sort of functionality, and have some implementation details in common. Use interface implementation, in order to signal that your classes provide some particular functionality (as specified by the interface).
Note that the two are not mutually exclusive; in fact if a superclass implements an interface, then any subclasses will also be considered to implement that interface.
In Java there is no multiple inheritance, so that a (sub)class can only have one parent class, and subclassing should be considered carefully so as to choose an appropriate parent if any at all; choosing a parent that reflects just a small amount of the class' abilities is likely to end in frustration later if there are other sensible parent classes. So for example, having an AbstractSQLExecutor with SQL Server and Oracle subclasses makes a lot of sense; but having a FileUtils parent class with some utility methods in, and then subclassing that all over the place in order to inherit that functionality, is a bad idea (in this case you should likely declare the helper methods static, or hold a reference to a FileUtils instance, instead).
Additionally, subclassing ties you to implementation details (of your parent) more than implementing an interface does. I'd say that in general it's better merely to implement the interface, at least initially, and only form class hierarchies of classes in the same or similar packages with a clear hierarchical structure.
Like you said. the implement java keyword is used to implement an interface where the extends is used to extend a class.
It depends what you would like to do. Typically you would use an interface when you want to force implementation (like a contract). Similar to an abstract class (but with an abstract class you can have non-abstract methods).
Remember in java you can only extend one class and implement zero to many interfaces for the implementing class. Unlike C# where you can extend multiple classes using :, and where C# only uses the : symbol for both interfaces and classes.
extends keyword is used for either extending a concrete/abstract class. By extending, u can either override methods of parent class / inherit them. A class can only extend class.
U can also say interface1 extends intenface2.
implements keyword is used for implementing interface. In this case u have to define all the methods indicated in interface. A class can only implement interface.

Categories