I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
A class can implement multiple interfaces, but it cannot implement multiple abstract classes.
Interface itself cannot do anything. It just defines kind of contract between the class(es) that provide some functionality and the caller.
Abstract class is the class that defined as abstract. If class has at least one abstract method (i.e. method without implementation) it must be defined as abstract. But abstract class can contain implementations as well.
Interface cannot contain implementation. Only abstract methods and constants (static final fields).
Class can implement several interfaces and extend only one class (including abstract class).
I hope this helps.
Abstract class can also contain function implementation rather than just defining the functions that have to be implemented by inheriting classes
Abstract classes are partially implemented classes, that will be extended by concrete classes(non-abstract), to be implemented.
Example:
This example does not mean that the sub classes must implement those methods(as it happens when implementing an interface). You can declare a subclass abstract, and the implementation will be done later by annother sub-sub-class. (For example: Boat can have subclasses "SpeedBoat" and FisshingBoat, and the may implement honk() in different ways)
The interface are the eyes of class to the outside world. What classes can do is declared in the interface, but implemented in the class.
A class can implement many interfaces, but can extend only one class.
See this little example of interfaces:
As you can see when we use interfaces we can have a lot of flexibility. Some Enemies can do things that some Heroes can do too(DarkKnight can throw arrows).
I hope you now feel the difference between the abstract classes and interfaces.
Remember this about interfaces and Abstract classes:
Interfaces dont have variables, just non implemented methods(abstract methods implicitly)
Classes that implement interfaces must have all the methods of the interface in its body
One class can extend only one class but implement more than one interface
If a class has an abstract method, it must bee declared as abstract.
Abstract classes can implement interfaces
Interfaces can extend other interfaces(more than one)
I dont know if i forget something, i hope this information helps.
An abstract class can everything that a Interface can do. However inverse of this is not correct.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.
We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed
Interface and abstract class almost both are same the major difference is using interface we are not able to define the body of the method but using abstract class we can define the body of the method inside the abstract class or while implementing it.
e.g
Interface abc()
{
string xyz();
}
abstract abc()
{
string xyz()
{
// define body
}
}
or
abstract abc()
{
string xyz();
}
An abstract class is a class - it defines all or part of an implementation of some behaviour for a class of objects, but with some extension points for concrete subclasses to provide.
An interface is a type - it defines the set of operations which are provided by any class implementing the interface.
You're almost asking whether there is anything that a candidate can do that the job description can't. Creating an abstract class says 'here is a template for some implementation'. Creating an interface says 'I expect an object to provide these capabilities'. You can use virtual methods in an abstract class to implement some aspects of a type, but the intention is different.
Related
I have an interface with several methods. I then have an abstract class that defines some of those methods, but also leaves some of the methods abstract. Now I have a class that extends the abstract class. Do I need to write all the methods from the original interface and define them, or does java know that some of them have been implemented by the abstract class?
At the point that you write a concrete (non abstract) class that implements an interface and/or is derived from an abstract base class, that concrete class must provide an implementation for every method it is specified as having. Specified means either by being declared abstract in a base class, or being specified by an interface that the class or one of its base classes declares it to implement.
If you write an abstract class that implements an interface and/or is derived from an abstract base class, your new class need not provide an implementation for any of the methods it is specified as having; those remaining methods are either explicitly or implicitly considered as being declared abstract by your new class.
Interfaces methods must be implemented. If the abstract class already implements some of them, you're free to override them in the subclasses or not.
In Interfaces, you declare some methods(), no actual implementation should be there.
And when you implement the interface into a abstract class, the declaration of those methods is present in that abstract class. It is up to you to decide whether to define the methods here or not.
when you extend these methods in concrete class(one which will be used to create objects), every methods needed to be defined and since if you already defined some methods in abstract class you don't need to do it again,but you can do it.
I know interface variables are always static because we can't make object of interface. But why not abstract class variables are always static? We cant make object of abstract class too
The main difference between interfaces and abstract classes is that - interfaces are just contracts, they are for specifying the signature of the methods that their subsequent concrete implementation must have, and all the methods in an interface are implicitly abstract.
In contrast, abstract classes are classes, they can have non-abstract methods with default implementation.
As quoted from JLS for the definition of an interface:
An interface declaration introduces a new reference type whose members are classes, interfaces, constants, and abstract methods. This type has no implementation, but otherwise unrelated classes can implement it by providing implementations for its abstract methods.
and the definition of an abtract class:
An abstract class is a class that is incomplete, or to be considered incomplete.
While interfaces do not do anything except specifying the pattern of the classes that implement them, abstract classes can do more - you can define their behavior - hence you can actually provide concrete implementation of their methods as well as defining their states (i.e. instance variables).
This is because the field of abstract class is then inherited by all subclasses and can be used by them. So, you can implement methods in your abstract class that deal with the logic related to such fields. You can think of an abstract class as a partially finished implementation; because it is partially finished, it cannot be constructed before it's completed by a subclass.
It is all explained by the implements vs. extends keywords: you're implementing the functionalities of an interface but are extending the capabilities of a (potentially abstract) class.
As you're extending, you inherit all of its fields and method in your instance.
You have instances of an abstract class as soon as you extend it: you're adding/changing functionalities to it, whereas an interface is merely an empty shell that you have to "fill in" with a behaviour.
I am now studying a java and I'm at the part of Abstract.
I read sorta strange part to me that there is an abstract class
which does not include any abstarct method.
Why do they use this kind of class?
To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.
A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.
Yes, we can have abstract class without any abstract method.
Best example of abstract class without any abstract method is HttpServlet
If this class extends another abstract class and don't have implementation of inherited abstract methods.
This class contains some common logic for all its inheritors, but itself does not represent usable entity (in terms of particular application)
These type of classes are used for a implement a general logic which can be implemented by other classes. Making it abstract prevents from instantiating it. But other classes can inherit the class and its methods.
Say you have a set of related classes, but no related (shared) code, yet. If we make all of these classes extend a base class with no abstract methods, that then if we wan't all of these classes to have an identical method/feature in the future, that can be done in one shot by putting it in the base class. So code is not repeated and it reflects in all child classes by including it in just one place.
Another example for having such class is when you implement creation helpers. These classes are used to ease the client in the creation of objects, which are related in topic but decoupled depending on the need. By nature, the methods of this creator classes are all static and they can be seen as utility classes as well.Obviously, instatntation of this classes is futile and hence the abstractkeyword.
To mention a recent example I met was the Sftpclass from org.springframework.integration.dsl.sftp which is basically an easy way to require objects (e.g: adapters, gateways) from the sftp api.
I develop a abstract class to prevent instantiation of that class and use it only as a base class. because, These type of classes are used for a implement a general logic which can be implemented by other classes. Sometimes, I have a default implementation for every method in abstract class. In the manner, it doesn't force the sub-class to override all of method, but also it implement everyone that is need.It means implicitly you have to override at least one method to make scene using this abstract class.
I can't think of any good reason to use it. It could be used as "marker" but an interface would be a better choice.
Abstract class without abstract method means you can create object of that abstract class.
See my Example.
abstract class Example{
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo
{
public static void main(String[] args)
{
Example ob = new Example(){};
ob.display();
}
}
If you write one abstract method inside abstract class then it will not compile.
Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.
What is use of an abstract class implementing an interface? In which
scenario would we implement.
Why would you choose Abstract class over interface? If an class
extends an Abstract class, should we implement all the methods in
the Abstract Class. If an class implements an Interface should we
implement all the methods too.
Why was abstract class or interface pattern introduced? What is the
use of them? Does it deal anything in the way object is getting
instantiated or the way it behaves?
If an abstract class has a static method declared, then can we
instantiate that class?
I was asked these questions, though my answers were not clear... i would like to know from people here?
1&2) You can use interfaces and abstract classes together -- the interface can provide a definition of behavior, and the abstract class provides partial implementation, the subclasses provide full implementation.
3) Interfaces and abstract classes are concepts. The java language designers decided to provide language features to realize the concepts.
4) An instance of an abstract class can never be instantiated. A static method on an abstract class can be invoked normally, remember static methods are invoked by referencing the class, not an instance of the class.
some psuedocode
abstract class Base {
abstract void doSomething(); // subclass provides implementation
protected helper() {
// doSomething implementation in subclass can use helper
}
}
On Abstract classes and Interfaces
Abstract classes defines a partial representation of some entity, that is common to every extending class but that must be completed by inheritance. So, every inheriting class comprehends all the properties defined in every parent classes.
Interfaces provide a behavior to a given class, and allow to simulate something similar to multiple inheritance. Since you can implement multiple interfaces in a class, you can make that class adopt the behavior of every implementing interface, and all together.
Classical example:
Abstract class: Animal Represents an animal in an abstract way. Each animal should extend this class to adopt all the implications of "being" an animal.
Abstract class: Mammal extends Animal The mammal is an Animal and inherits all the properties that are common to every mammal.
Some mammals are carnivorous and some herbivorous. These are different behaviors for the same type of animal, so here they come the interfaces.
Interface: Carnivorous Defines the properties a carnivore animal should have.
Interface: Herbivorous Defines the properties a herbivore animal should have.
Every mammal should breath air. This is another behavior, that is common to every mammal.
Interface AirBreathing Defines the properties for air-breathing animal
So. You have these two mammals: Wolves and Manatees. Both have to breath air, but wolves are carnivorous and manatees herbivorous.
Class Wolf extends Mammals implements AirBreathing, Carnivorous
Class Wolf extends Mammals implements AirBreathing, Herbivorous
Implementation details
1) Every abstract method defined in an abstract class, must be implemented somewhere "in the road" of inheritance until a final class is reached. This means that when a final class is implemented it must implement or inherit implementations of every abstract method inherited from parent classes.
2) Yes, you can define static methods in abstract classes. You can call static method from the abstract class as AbstractClass.staticMethod(), but you can't ever instantiate an abstract class.
3) Classes implementing interfaces, must implement every method defined by the interface.
Hope this helps.
What is use of an abstract class implementing an interface? In which scenario would we implement?.
One important use is to provide a skeletal implementation reducing the effort needed to implement the interface. An example of this is AbstractCollection<E> which implements the Collection<E> interface in the Java Collections Framework.
Why would you choose Abstract class over interface?
When I want to provide an implementation for some parts of the class's behaviour.
If a class extends an abstract class, should we implement all the methods in the abstract
Class. If an class implements an interface should we implement all the methods too.
Concrete classes must completely implement the abstract interface. You have no choice but to implement all methods. This is because whenever you implement an interface or extend an abstract class with a concrete implementation, you're declaring that the concrete class fully describes the interface's behavior.
Of course abstract extensions don't have to implement the interface completely i.e. abstract extensions of interfaces / abstract classes aren't forced to implement the interface in entirety.
Why was abstract class or interface pattern introduced? What is the use of them? Does it deal anything in the way object is getting instantiated or the way it behaves?
Interfaces describe the behavior of types. Since all implementations must completely describe the behavior enforced by the interface, they allow for polymorphism.
Canonical Collections Framework example:
The List<E> interface describes how a list of objects may behave. It describes the add, remove, get and set operations to name a few.
2.ArrayList<E> and LinkedList<E> are two concrete implementations of the List<E> interface.
3.Thus it's guaranteed that both of them behave like a List<E> and more specifically have concrete implementations of the add, remove, get and set operations to name a few.
4.Also since both of them implement the same interface, more specifically, both of them behave like a List<E>, I can use them, wherever I need to use a List<E>.
5.This allows for statements like these :
List<String> names = new ArrayList<String>();
List<String> queue = new LinkedList<String>();
showList(names);
showList(queue);
void showList(List<String> list) {
for(String s : list)
System.out.println(s);
}
This is a very simple example of polymorphism in action. The showList(List<String> list) methods accepts and happily iterates over names and queues because both of them implement the same interface and it can be sure of it's behaviour.
I have just completed my studies and joined a firm. So might be possible i may not be able to give you good example but yes in broad sense they gonna work and they are effective...
the most important reason for using interface is to create a common behavior in related classes. Wonderfull example is collection framework. Collection is a interface that ensure whatever the classes that represents collection of some objects then it should compulsory implement all the methods of collection(else they wont be a collection, also note that collection is a behavior) and now this interface is further implemented by other interface list so all the collection which are of type list implement this(here we have specialize the behavior of collection(by adding some method), note that list is also a behavior). Now we want a class which represents nothing but a collection of array as linked list so we implemented all the methods of list(which ultimately have collection method).
Now come to abstract class, consider the example of Number class in java its a abstract class which implements serializable interface since it has to show serialized behavior. Also note that Number represents some physical entity, so it should be a abstract class. Abstract because from it we cant conclude to exact object. While serializable is a behavior hence interface.
Thats what i could deliver to you and thats what i learned from my basic knowledge. But always remember oops differ people to people. See your encapsulation implement abstraction example as well. So everything depends on you.
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