Saturday, May 6, 2023

10 Abstract Class and Interface Interview Questions Answers in Java

Abstract class and interface are very popular in any object-oriented programming language or Java interview, and there are always one or more questions from this. The interface is more common, because of its popularity among designers but questions from abstract class also pop up now and then. Interview questions from the abstract class are 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, like the Decorator pattern or Factory pattern.

Anyway, in this article, we will see a mix of these interview questions from abstract class and interface. All questions have been asked in various Java interviews and the difficulty level for these questions is easy for most Java developers. 

It’s mostly fact-based questions, but some questions like the difference between abstract class and interface in Java, and when to prefer abstract class over interface can be really tricky.

Btw, if you are new to the world of object-oriented programming and design then I also suggest you go through a hands-on course like UML and Object-Oriented Design Foundations by Karloy Neisztor on Udemy. It's a great course to understand the complete process of object-oriented analysis and design for creating quality software.



10 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, then please share with us as a comment

1. Can abstract classes have constructors in Java?

Yes, an abstract class can declare and define a constructor in Java. Since you can not create an instance of an abstract class, a constructor can only be called during constructor chaining, i.e. when you create an instance of the concrete implementation class. 

Now some interviewer, ask what is the purpose of a constructor if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside an abstract class, and used by the various implementation. 

Also even if you don’t provide any constructor, the compiler will add a default no-argument constructor in an abstract class, without that your subclass will not compile, since the first statement in any constructor implicitly calls super(), default superclass constructor in Java.



2. Can abstract class implement interface in Java? do they require to implement all methods?

Yes, an abstract class can implement an interface by using the 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 the burden of implementing all methods, had they implemented List interface directly. 

It’s the best of both worlds, you can get the advantage of interface for declaring type, and flexibility of abstract class to implement common behavior in one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.




3. Can an abstract class be final in Java?

No, an abstract class can not be final in Java. Making them final will stop the abstract class from being extended, which is the only way to use an 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. The bottom line is, you can not make your class abstract and final in Java, at the same time, it’s a compile-time error.

10 Abstract Class and Interface Interview Questions Answers in Java



4. Can abstract classes have static methods in Java?

Yes, an abstract class can declare and define static methods, nothing prevents doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in an object-oriented design, because static methods can not be overridden in Java. It’s very rare, you see static methods inside an abstract class, but as I said, if you have a very good reason for doing it, then nothing stops you.



5. Can you create an instance of an abstract class?

No, you can not create instances of abstract class in Java, they are incomplete. Even though, if your abstract class doesn’t contain any abstract method, you can not create an instance of it. By making a class abstract,  you told the compiler that, it’s incomplete and should not be instantiated. Java compiler will throw an error when a code tries to instantiate an abstract class.



6. Is it necessary for an abstract class to have an abstract method?

Java abstract class and interface interview Question answersNo, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using the abstract keyword in the class declaration. The compiler will enforce all structural restrictions, applied to an abstract class, like,  not allowing to create of any instance. 

By the way, it’s debatable whether you should have an abstract method inside the abstract class or interface. In my opinion, the abstract class should have abstract methods, because that’s the first thing programmer assumes when he sees that class. That would also go nicely along with the 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 questions. 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 the ability to produce examples. 

It’s easy to answers questions on core OOP concepts like Abstraction, Encapsulation, Polymorphism, and Inheritance, but when it comes to subtle points like this, a candidate more often fumbled. You can see this post for all syntactical differences between abstract class and interface, but it deserves a post on its 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 the 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 a concern. 

Abstract class in Java evolves better than the interface. Similarly, if you have too many methods inside the interface, you are creating pain for all its implementation, consider providing an abstract class for default implementation. This is the pattern followed in the Java collection package, you can see AbstractList provides a default implementation for the List interface.



9. What is the abstract method in Java?

An abstract method is a method without a body. You just declare the method, without defining it and use abstract keywords in the method declaration.  All methods declared inside Java Interface is by default abstract. Here is an example of an abstract method in Java

                public void abstract printVersion();

Now, In order to implement this method, you need to extend the abstract class and override this method.



10. Can an abstract class contains the main method in Java?

Yes, an abstract class can contain the main method, it just another static method and you can execute the Abstract class with the 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 the FAQ for abstract class, nice to refresh, before going to the interview. On a 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.

Further Learning
SOLID Principles of Object-Oriented Design
Absolute Introduction to Object-Oriented Programming in Java
Java - Object-Oriented Programming [For Absolute Beginners]

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

Unknown 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

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

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

Avinash Bhardwaj said...

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.

Anonymous said...

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.



Karthick said...

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.

javin paul said...

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

Karthick said...

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

javin paul said...

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

Unknown said...

@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();
}



}

Anonymous said...

No Interface is a class like which is completely abstract. class implements interface

Anonymous said...

No constructor cannot be declared in the class as constructor is not an abstract might have changed in version 8

Anonymous said...

There will be no compile time or run time exception as method signature is same n same return type.
In this case even if you have interface reference of X Or Y then also only implemented method will be called.
Now suppose u have same method in both interfaces but different return type n when you try to implement them in class then compiler will compile issue as duplicate method not allowed.

androidgoal said...

Question was old but impressive :) Can this be a solution? Create a new abstract class and implement the ABC interface and declare your new function without any body inside your new abstract class without implementing the body. New classes or the existing one which want to implement the new function should re-extend abstract one instead of implementing the interface?

lingmaaki said...

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. But if we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.....more

Ling

Unknown said...

Make another interface which contains required method and make this parent inerface of Abc.

ashishb said...

No ambiguity because, what each and every time u need to implement methods defination which are there in Interface. So method name same in 2 different interface doesn't matter as they hav single implementation in there completed class

Anonymous said...

@Neerag, here the solution for your query
Interface A{
void sumof2();
Interface B{//Inner Interface
void sumof3();
}
}
class AA imp A{
@override
public void sumof2(){
//do somethig...
}
}
class AB imp A,A.B{
@override
public void sumof2(){
//do somethig...
}
@override
public void sumof3(){
//do somethig...
}
}

Proud Prajaakeeyan! said...

Hope it depends on the requirement. If it is mandatory to implement in all classes then we will go ahead and add the method in interface and will implement the overridden method in all class. If it is required in few classes only then we can either choose to give default method or static method implementation in interface and same can be called in other classes. Or else as every one says we can go for new interface or abstract method approach.

Unknown said...

No ,we cannot declare constructor in interface because in interface we can have only final and static member whose intialization is taken care by jvm and it is done at compile time .

Unknown said...

We Cannot declare constructor in interfaces as the main propose of the constructor is to internalized the instance variable and in interface all t he variables are by public static final static hence we cant declare constructor inside interface as there is no instance variable

Yoan said...

You can make another interface as @syed and others say or favor encapsulation over inheritance. Create one class B that implements all the interface methods and then declare a member variable B inside each class that implements the interface. You may call interface behavior like B.m1(), b.m2() etc. The original design violate the principle of encapsulation. See strategy design pattern for a better idea of what I’m saying.

Unknown said...

Good post. You should extend thé questions with SOLID Principles...

Unknown said...

same question was asked to me in interview and i had given ans as u say.. interviewer was not satisfied

Unknown said...

Hi neeraj you use default method in interface

Unknown said...

Make that method default in the given interface and give default implementation there

javin paul said...

@Unknown, Yes, Java 8 has made a lot of things easier in Java.

Unknown said...

No,

Deepa said...

Java 7 implementation
package com.java.revisit.iq;

interface InterfaceOne {
void doAction1();

interface InterfaceTwo {
void doAction2();
}
}


package com.java.revisit.iq;



public class AbsractVsInterfaceOne implements InterfaceOne {

@Override
public void doAction1() {
// TODO Auto-generated method stub

}

}


package com.java.revisit.iq;



public class AbsractVsInterfaceTwo implements InterfaceOne {

@Override
public void doAction1() {
// TODO Auto-generated method stub

}

}


package com.java.revisit.iq;



public class AbsractVsInterfaceThree implements InterfaceOne,InterfaceOne.InterfaceTwo {

@Override
public void doAction1() {
// TODO Auto-generated method stub

}

@Override
public void doAction2() {
// TODO Auto-generated method stub

}

}

Unknown said...

Tq for your questions and answers

Unknown said...

By making that method default you can solve the problem. As java 1.8 allows to make methods static and final.

Post a Comment