Abstract class and interface is very popular in any object oriented
programming language or Java interview, and there are always one or more
questions from this. Interface is more common,
because of its popularity among designers but questions from abstract class
also pops up now and than. Interview questions from abstract class is more
common on junior level or you say under 2 years experience of Java programmers, while interface related
questions are mostly asked on senior level Java interview e.g. 4 or 6 years of
experience. They are mostly asked along with other Java design pattern questions,
e.g. Decorator pattern or Factory pattern . Any way, in
this article we will see mix of these interview questions from abstract class
and interface. All questions has been asked in various Java interviews and
difficulty level for these question is easy for most of Java developer. It’s
mostly fact based questions, but some questions like difference between abstract class and interface in Java, and when to prefer abstract class over interface
can be really tricky.
Frequently asked Abstract class and Interface questions in Java
Here is my list of questions, this not only explains rules related to
abstract class but also shares some tricky questions about using abstract class
and interface. If you have asked any question on this topic, which you don’t
see in this list, than please share with us as comment1) Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you
can not create instance of abstract class,
constructor can only be called during constructor chaining, i.e.
when you create instance of concrete implementation class. Now some
interviewer, ask what is the purpose of constructor, if you can not instantiate
abstract class? Well, it can still be used to initialize common variables,
which are declared inside abstract class, and used by various implementation. Also
even if you don’t provide any constructor, compiler will add default no argument constructor
in abstract class, without that your subclass will not compile, since first
statement in any constructor implicitly calls super(), default
super class constructor in Java.
2) Can abstract class implements interface in Java? does they require to implement all methods?
Yes, abstract class can implement interface by using implements keyword.
Since they are abstract, they don’t need to implement all methods. It’s good
practice to provide an abstract base class, along with an interface to declare
Type. One example of this is java.util.List interface
and corresponding java.util.AbstractList abstract class. Since AbstractList implements
all common methods, concrete
implementations like LinkedList and ArrayList are free from burden
of implementing all methods, had they implemented List interface
directly. It’s best of both world, you can get advantage of interface for
declaring type, and flexibility of abstract class to implement common behavior
at one place. Effective Java has a nice
chapter on how to use interface and abstract class in Java, which is worth
reading.
3) Can abstract class be final in Java?
No, abstract class can not be final in Java. Making them final will stop
abstract class from being extended, which is the only way to use abstract
class. They are also opposite of each other, abstract keyword
enforces to extend a class, for using it, on the other hand, final keyword prevents a class
from being extended. In real world also, abstract signifies incompleteness,
while final is used to demonstrate completeness. Bottom line is, you can not
make your class abstract and final in Java,
at same time, it’s a compile time error.
4) Can abstract class have static methods in Java?
Yes, abstract class can declare and define static methods, nothing
prevents from doing that. But, you must follow guidelines for making a method
static in Java, as it’s not welcomed in a object oriented design, because static methods can not be overridden in
Java. It’s very rare, you see static methods inside abstract class,
but as I said, if you have very good reason of doing it, then nothing stops
you.
5) Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are
incomplete. Even though, if your abstract class don’t contain any abstract
method, you can not create instance of it. By making a class abstract, you told compiler that, it’s incomplete and
should not be instantiated. Java compiler will throw error, when a code tries
to instantiate abstract class.
6) Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method.
You can make a class abstract in Java, by just using abstract keyword in
class declaration. Compiler will enforce all structural restriction, applied to
abstract class, e.g. now allowing to create any instance. By the way, it’s
debatable whether you should have abstract method inside abstract class or
interface. In my opinion, abstract class should have abstract methods, because
that’s the first thing programmer assumes, when he see that class. That would
also go nicely along principle of least surprise.
7) Difference between abstract class and interface in Java?
This is the most important and one of the classic Java Interview
question. I don’t know, how many times I have seen this question at all most
all levels of Java interviews. One reason, which makes this question
interesting is ability to produce example. It’s easy to answers questions on
core OOPS concepts like Abstraction, Encapsulation, Polymorphism and Inheritance, but when it comes
to subtle points like this, candidate more often fumbled. You can see this post
for all syntactical difference between abstract class and interface, but it
deserve a post on it’s own.
8) When do you favor abstract class over interface?
This is the follow-up of previous interview questions on abstract class
and interface. If you know syntactical difference, you can answer this question
quite easily, as they are the one, which drives the decision. Since it’s
almost impossible to add a new method on a published interface, it’s better to
use abstract class, when evolution is concern. Abstract class in Java evolves
better than interface. Similarly, if you have too many methods inside
interface, you are creating pain for all it’s implementation, consider
providing an abstract class for default implementation. This is the pattern
followed in Java collection package, you can see AbstractList provides
default implementation for List interface.
9) What is abstract method in Java?
An abstract method is a method without body. You just declare method,
without defining it and use abstract keyword in method
declaration. All method declared inside Java Interface are by default
abstract. Here is an example of abstract method in Java
public
void abstract printVersion();
Now, In order to implement this method, you need to extend abstract class
and override this method.
10) Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another
static method and you can execute Abstract class with main method, until you
don’t create any instance.
That’s all on this list of interview questions on abstract class,
interface and methods in Java. You can also bookmark this list as FAQ for
abstract class, nice to refresh, before going to interview. On different note,
abstract class and interface are key design decisions on object oriented analysis
and design process, and should be taken by applying due diligence, of course if
you want to write flexible systems.
27 comments :
Can anyone please advise on Below question, I was recently asked this question on a Java Interview with Nomura Mumbai :
Suppose you have an interface say ABC, which has been implemented by dozens of classes. Now you need to add another method in that interface ABC. What would be your approach to make that change in minimal way to solve the problem of overriding that method in all implementing classes?
I tried to give answer by making an abstract class to implement interface ABC, and then making each of client class to extend from Abstract class, but interviewer was not satisfied, he also raise concern, like what would happen if one of the client classes is already extend another class, Since in Java you can only extend one class, how would you solve that.
Please share your view.
@Neeraj, Interface is almost immutable, once published, any modification on interface e.g. adding method will result in breaking of all clients. I think best way possible is to declare that method in another interface and let only classes needed that method implements new interface as well. I know, this is not the clean solution, and like a work around, but interface in Java are like that, that's why using abstract class is better choice, when evolution is concern. If anyone has any other idea, than please share.
Hi @Neeraj.. I will answer your question as below
1) create one new Abstract class which implements original interface.. Add new method into this abstract class with default implementation
2)modify all classes which implemented original interface such way that.. they will extend new abstract class created in step1 rather than implementing original interface..
I believe these changes are minimal and still achieving desired functionality
@Javin , I think this is the best way or the only way to solve it.
The minimal change could be to make all the classes as an abstract class.
--Kaustubh
One other way, I could think of is to have a new Interface, say XYZ (with just the new method) extend the original Interface, ABC. And then have the classes requiring the new method implement Interface XYZ instead of ABC.
@Saurabh, having different interface with different functionality is better choice. I think Creating another interface with new method is better choice, because in future if anyone wants just this new method, they only need to implement this new interface.
This problem will be solved by Java 8, Default/Defender methods. Essentially you would be able to appoint a default implementation of a given method in an interface.
Yes this will introduce a limited, code level, multiple inheritance support.
@Neeraj Instead of creating a new abstract class or another interface (I think the requirement is the new method in the same interface), I would suggest empty methods for void return type, or null returning methods for non-void return type, in the subclasses where there is no required implementation until the time.
-Abhishek
Is Abstract Class Should always be declared as parent class?
@N.Srikanth, YES, because they are abstract and until Child class extends them, you just can not use them.
One question, which you might want to include is, Why do you need interface if you can not define any method there? In fact, what is the use of interface in Java? I have seen this question in various forums, my answer would be. Interface is great to define Type and since Java class can implement multiple interface, using it to define Type is a right choice. It's impossible for a class to be of Serializable and Cloneable if they were not interface.
One question related to Java interface, which is asked recently to me was, suppose you have two interface X and Y with identical method with same signature and same return type e.g. public String name() and now if a class Z implements both X and Y and overrides name() method, what would happen? compile time error, runtime exception or simply runs fine? I tried that in IDE and it runs fine, but I need proper explanation as why not compiler report any error related to ambiguous call, when we used C's object for calling name e.g. c.name()
Hello Sir, Can we declare an interface inside a class? is it possible in Java, if yes then can you please give an example of when to create an interface inside a concrete class in Java.
Hi gouri--What is C in your comment?
i am Expecting it might be a class because of your eg:c.name(and c is object of C class);
if it is then tell me how it relates to your problem?
Can we declare constructor inside interfaces? if yes, what is the purpose of adding constructor on interface, because we can not create object of interface in Java? this was asked to one of my friend in Goldman Sachs Interview.
Gauri... I am considering as 'c' is an instance of class Z which implements both X and Y interface. The answer based on this situation is even if you mentioned both interface with a same method with same siganture and arugument list.. the compiler looks for definition of the interface method in implemented class, let's see it's look for interface X where compiler found the implementation for name() method in class Z. The same will happen with interface Y. The compiler doesn't bother about both interface having same method. So it compiles fine.
The things is that whenever you are calling method x c = new Z() and u r trying to call c.anme() the declaration of name method is available in implemented interface X and the definition is also given in Class Z so at runtime it also work fine..
Can we declare constructor inside interfaces? if yes, what is the purpose of adding constructor on interface, because we can not create object of interface in Java? this was asked to one of my friend in Goldman Sachs Interview.
Ans. No we can't create constructor inside interface. The reason is that, Interface is solely dedicated to standards.. which means it is just contract... if you implement it then you should follow the contract.. It will not going to responsible for any specific behaviour or also it is not dedicated to any hierarchy level. It can be implemented by any one who gives specific behaviour for that contract...
I think all the work around that you guys are saying can work well, but it is not going to satisfy the interviewer, as he may be trying to check that how much you are updated with the technology you are involved in ...
Agree with h143570 said... Java 8 is going to give this facility of creating Default/Defender methods in interfaces which will allow developers to add methods/implementation at very late stage of the development.
Kindly check Java 8 new features.
Gauri.., The problem occurs in multiple inheritance when you have more than one implementation at runtime and ambiguity arise when JVM has to decide which one to call.. but when it is supported by interface this gets resolved because you will get only one copy of implementation at runtime..
for eg. you have name() in Interface X and Y both but when you implement it, you have only one copy of implementation which has two identifier i.e. X.name() and Y.name() so here JVM has no pain to use their brain to call the implementation logic.
It has same behavior like you declare String a="Java" and String b="Java" ... same value of object but two identifier.
Using Default/Defender methods in java8 is a solution.
For earlier versions. Create a new interface XYZ for new methods. Now the interface ABC can extend the interface XYZ. Subclasses of ABC can override the method in XYZ.
@Karthick, Default method is indeed the best solution if you are lucky to use Java 8 in production code. Regarding your second solution, don't you think it's same as as adding a new method in existing interface ABC, because then also all implementation of ABC has to implement that method. Did you mean that the class which needs these new method, only those should implement the new interface XYZ? because then impact will only be limited to those class which needs that method and not all implementor classes of ABC.
@Javin: Otherwise, all sub classes whichever needs new methods should implement XYZ(New interface with new methods) in addition to ABC(Old Interface). I think it is better instead of extending ABC with XYZ.
@Kathick, Indeed that's the most practical solution keeping backward compatibility in mind. But even this is not free from hassles, because it might be possible some code written using ABC needs to duplicated to accommodate XYZ. It's best suited when new method is implemented via completely new code. An example will explain it better, let's take example or Runnable and Callable, they didn't added call() to Runnable instead gone for new interface, but this has consequence that you can not pass Callable to a method which is expecting Runnable.
@Neeraj,
my version of solution for your question:
package com.example.interfaces;
public interface Student {
public void study();
class Inner{
public void doSomething(){
System.out.println("common method for all classes which extends Student interface");
}
}
Inner obj = new Inner();
public void doSomething();
}
package com.example.interfaces;
public class ConcreteStudent implements Student {
@Override
public void doSomething() {
obj.doSomething();
}
@Override
public void study() {
}
public static void main(String args[]){
ConcreteStudent student = new ConcreteStudent();
student.study();
}
}
No Interface is a class like which is completely abstract. class implements interface
No constructor cannot be declared in the class as constructor is not an abstract might have changed in version 8
Post a Comment