Few Questions over abstract class and interface in java? - java

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.

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.

Java Collections: Interfaces and Abstract classes

All Collections implements interface Collection, these collection have specific abstract hierarchy e.g.
AbstractCollection -> AbstractList -> ArrayList
AbstractCollection -> AbstractSet -> HashSet
But there are also corresponding interfaces like Collection, List, Set. These interface seem to me kind of redundant.
Why are they here ? Is is just convention or is there a reason to just implement interface and not extend the abstract class.
The interfaces are there because it's good to be able to assign a type to a variable or parameter without imposing an implementation.
For instance if I create a persistent entity to use in Hibernate, and it has a collection of things, I want to assign a type of List or Set to that. Hibernate will swap out whatever list I initialize it to with its own, with some Hibernate-specific implementation that does lazy-loading or whatever else it needs to. The Hibernate developers may not want to be constrained by having to extend the abstract class.
The abstract class exists as a convenience for implementers. The interface is a contract used by clients.
Implementing an interface is much different from extending an abstract class.
Let's suppose that class Animal is an abstract class, and that Dog, Cat, Snake and Shark extend Animal.
The default Animal.move() implementation simply moves them.
But, interfaces allow us to further group-out similar animals, such as RunningAnimal, SwimmingAnimal.
So, if Dog extends Animal implements RunningAnimal, along the inherited move() he will also have to implement his own run(), which might find it's way in the overridden move() inherited from Animal. Does this make sense to you yet or do I need to clarify better / with some code? :)
Interfaces let you group similar functionality of different classes. "Clickable", "Sortable", "Serializable" ... They all encompass the members thru a shared functionality (so a list of clickables is more than a list of buttons) rather than a same purpose.
So, think about it like this
Cat extends Animal implements RunningAnimal, ClimbingAnimal -- inherits move() has to implement run() and climbTree()
Dog extends Animal implements RunningAnimal -- inherits move(), has to implement run()
Snake extends Animal -- likely overrides inherited move()
Shark extends Animal implements SwimmingAnimal -- likely overrides move(), has to implement swim()
Why not ? Abstract classes are made to simplify inheritance process. When you want to create your collection you don't have to do everything from scratch.
But of course no one tells you that you SHOULD inherit from AbstractCollection. You can write your implementation from scratch.
This is a common good practice for API's to have interfaces. And have distinction between implementations and interfaces.
An Interface is a contract made between users and implementers. An abstract base class is intended to be used as a common base to access a number of similarly-behaving objects.

abstract classes ,constructor and interface

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.

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

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