Tuesday, April 16, 2013

10 Abstract Class and Interface Interview Questions Answers in Java

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

Java abstract class and interface interview Question answersHere 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 comment


1) 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.

18 comments :

Neeraj said...

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.

Javin @ Connection refused exception in Java said...

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

inj rav said...

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

ramesh said...

@Javin , I think this is the best way or the only way to solve it.

Apte Kaustubh said...

The minimal change could be to make all the classes as an abstract class.
--Kaustubh

Saurabh said...

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.

Rakesh said...

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

h143570 said...

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.

Anonymous said...

@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

N. Srikanth said...

Is Abstract Class Should always be declared as parent class?

Pushpa said...

@N.Srikanth, YES, because they are abstract and until Child class extends them, you just can not use them.

Pushkar said...

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.

Gauri said...

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()

Gauri said...

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.

N. Srikanth said...

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?

Anonymous said...

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.

Anonymous said...

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

Anonymous said...

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

Post a Comment