It contains Java Interview questions from SOLID design principles, OOP fundamentals e.g. class, object, interface, Inheritance, Polymorphism, Encapsulation, and Abstraction as well as more advanced concepts like Composition, Aggregation, and Association. It also contains questions from GOF design patterns.
List questions:
- Object oriented Programming (OOP)
- What is a POJO?
- What is JavaBean?
- Differences between POJO and JavaBean?
- What is the difference between an Interface and an Abstract class?
- What is the different between a constructor and a method?
- State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
- What is an abstract class? How is it different from an interface? Why would you use it?
- Does Java support multiple inheritances?
- Which design pattern have you used in your production code? apart from Singleton?
- Can you explain Liskov Substitution principle?
- What is Law of Demeter violation? Why it matters?
- What is Adapter pattern? When to use it?
- What is "dependency injection" and "inversion of control"? Why would someone use it?
- Which one is better constructor injection or setter dependency injection?
- What is difference between dependency injection and factory design pattern?
- Difference between Adapter and Decorator pattern?
- Difference between Adapter and Proxy Pattern?
- What is Template method pattern?
- When do you use Visitor design pattern?
- When do you use Composite design pattern?
- The difference between Inheritance and Composition?
- What is the difference between overloading and overriding
- Can you override a private or static method in Java?
- What is meant by Inheritance and what are its advantages?
- What is the difference between this() and super()?
- What modifiers may be used with top-level class?
- The difference between nested public static class and a top level class in Java?
- Difference between Composition, Aggregation and Association in OOP?
- Give me an example of design pattern which is based upon open closed principle?
- Difference between Abstract factory and Prototype design pattern?
- When do you use Flyweight pattern?
- Procedural Programming vs Object-Oriented Programming
- What is the purpose of abstraction in software development?
- What is encapsulation? How does Java support it?
- What is polymorphism? How does Java support it?
- What is the difference between a mutable object and an immutable object? How can you design an object to be immutable?
- What is the difference between coupling and cohesion? What is the preferred relationship between software components and why?
- What is Static Binding and Dynamic Binding?
-
Object oriented Programming (OOP) ⤴
Java is a computer programming language that is concurrent, class-based and object-oriented.
Object Oriented Programming System is the programming technique to write programs based on the real world objects. The states and behaviors of an object are represented as the member variables and methods. In OOPS programming programs are organized around objects and data rather than actions and logic.
The advantages of object oriented software development are shown below:
- Simplicity: OOPS programming objects model real world objects, so the complexity is reduced and the program structure is clear.
- Modular development of code, which leads to easy maintenance and modification.
- Extensibility: Adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones.
- Reusability of code.
- Improved reliability and flexibility of code.
- Increased understanding of code.
Object-oriented programming contains many significant features, such as encapsulation, inheritance, polymorphism and abstraction. We analyze each feature separately in the following sections.
Encapsulation
Encapsulation provides objects with the ability to hide their internal characteristics and behavior. Each object provides a number of methods, which can be accessed by other objects and change its internal data.
In Java, there are three access modifiers: public, private and protected. Each modifier imposes different access rights to other classes, either in the same or in external packages. Some of the advantages of using encapsulation are listed below:
- The internal state of every objected is protected by hiding its attributes.
- It increases usability and maintenance of code, because the behavior of an object can be independently changed or extended.
- It improves modularity by preventing objects to interact with each other, in an undesired way.
You can refer to our tutorial here for more details and examples on encapsulation.
Polymorphism
Polymorphism is the ability of programming languages to present the same interface for differing underlying data types. A polymorphic type is a type whose operations can also be applied to values of some other type.
Inheritance
Inheritance provides an object with the ability to acquire the fields and methods of another class, called base class. Inheritance provides re-usability of code and can be used to add additional features to an existing class, without modifying it.
Abstraction
Abstraction is an OOPS concept to construct the structure of the real world objects. During this construction only the general states and behaviors are taken and more specific states and behaviors are left aside for the implementers.
Differences between Abstraction and Encapsulation
-
Abstraction and encapsulation are complementary concepts. On the one hand, abstraction focuses on the behavior of an object. On the other hand, encapsulation focuses on the implementation of an object’s behavior. Encapsulation is usually achieved by hiding information about the internal state of an object and thus, can be seen as a strategy used in order to provide abstraction.
-
Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using four types of access level modifiers: public, protected, no modifier and private.
-
What is a POJO? ⤴
-
What is JavaBean? ⤴
-
Differences between POJO and JavaBean? ⤴
-
What is the difference between an Interface and an Abstract class? ⤴
An Interface is a Class with no implementation. You can not create an object from an interface as it has no implementation or fields. (Interface can contain only public static final fields)
An Abstract Class is another type of Class. It may have some methods which have not been implemented (which will be labeled abstract), but it may also have some methods which have been implemented. Abstract Class also can not be used to create an object, as some implementation code will be missing. (Abstract class can contain regular class fields)
An object can only be instantiated based on a full class (not abstract, not an interface). In Java, a class can implement between zero or many interfaces, or it can extend zero or one abstract or concrete class only.
When to use abstract class and interface in Java
- An abstract class is good if you think you will plan on using inheritance since it provides a common base class implementation to derived classes.
- An abstract class is also good if you want to be able to declare non-public members. In an interface, all methods must be public.
- If you think you will need to add methods in the future, then an abstract class is a better choice. Because if you add new method headings to an interface, then all of the classes that already implement that interface will have to be changed to implement the new methods. That can be quite a hassle.
- Interfaces are a good choice when you think that the API will not change for a while.
- Interfaces are also good when you want to have something similar to multiple inheritance, since you can implement multiple interfaces.
- An abstract class is good to define default behavior for a family of class, but the interface is good to define Type which is later used to leverage Polymorphism.
References: programmerinterview, javarevisited, other
-
What is the different between a constructor and a method? ⤴
-
State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers. ⤴
-
What is an abstract class? How is it different from an interface? Why would you use it? ⤴
An abstract class is a java class that has one or more abstract methods (no body). Abstract class can not be instantiated. Abstract class defines an interface that has to be implemented by all its subclasses.
An abstract class is a class which can have state, code and implementation
-
Does Java support multiple inheritances? ⤴
This is the trickiest question in Java if C++ can support direct multiple inheritance than why not Java is the argument Interviewer often give.
Answer of this question is much more subtle then it looks like, because Java does support multiple inheritances of Type by allowing an interface to extend other interfaces, what Java doesn't support is multiple inheritances of implementation.
This distinction also gets blur because of default method of Java 8, which now provides Java, multiple inheritances of behavior as well. See Why multiple inheritance is not supported in Java to answer this tricky Java question.
-
Which design pattern have you used in your production code? apart from Singleton? ⤴
This is something you can answer from your experience. You can generally say about dependency injection, factory pattern, decorator pattern or observer pattern, whichever you have used. Though be prepared to answer follow-up question based upon the pattern you choose.
-
Can you explain Liskov Substitution principle? ⤴
This is one of the toughest questions I have asked in Java interviews. Out of 50 candidates, I have almost asked only 5 have managed to answer it. I am not posting an answer to this question as I like you to do some research, practice and spend some time to understand this confusing principle well.
-
What is Law of Demeter violation? Why it matters? ⤴
Believe it or not, Java is all about application programming and structuring code. If you have good knowledge of common coding best practices, patterns and what not to do than only you can write quality code.
Law of Demeter suggests you "talk to friends and not stranger", hence used to reduce coupling between classes.
-
What is Adapter pattern? When to use it? ⤴
Another frequently asked Java design pattern questions.
It provides interface conversion.
If your client is using some interface but you have something else, you can write an Adapter to bridge them together. This is good for Java software engineer having 2 to 3 years experience because the question is neither difficult nor tricky but requires knowledge of OOP design patterns.
-
What is "dependency injection" and "inversion of control"? Why would someone use it? ⤴
-
Which one is better constructor injection or setter dependency injection? ⤴
Each has their own advantage and disadvantage.
Constructor injection guaranteed that class will be initialized with all its dependency, but setter injection provides flexibility to set an optional dependency.
Setter injection is also more readable if you are using an XML file to describe dependency.
Rule of thumb is to use constructor injection for mandatory dependency and use setter injection for optional dependency.
-
What is difference between dependency injection and factory design pattern? ⤴
Though both patterns help to take out object creation part from application logic, use of dependency injection results in cleaner code than factory pattern.
By using dependency injection, your classes are nothing but POJO which only knows about dependency but doesn't care how they are acquired.
In the case of factory pattern, the class also needs to know about factory to acquire dependency.
Hence, DI results in more testable classes than factory pattern. Please see the answer for a more detailed discussion on this topic.
-
Difference between Adapter and Decorator pattern? ⤴
Though the structure of Adapter and Decorator pattern is similar, the difference comes on the intent of each pattern.
The adapter pattern is used to bridge the gap between two interfaces.
But Decorator pattern is used to add new functionality into the class without the modifying existing code.
-
Difference between Adapter and Proxy Pattern? ⤴
Similar to the previous question, the difference between Adapter and Proxy patterns is in their intent. Since both Adapter and Proxy pattern encapsulate the class which actually does the job, hence result in the same structure.
But Adapter pattern is used for interface conversion while the Proxy pattern is used to add an extra level of indirection to support distribute, controlled or intelligent access.
-
What is Template method pattern? ⤴
Template pattern provides an outline of an algorithm and lets you configure or customize its steps.
For examples, you can view a sorting algorithm as a template to sort object. It defines steps for sorting but let you configure how to compare them using Comparable or something similar in another language.
The method which outlines the algorithms is also known as template method.
-
When do you use Visitor design pattern? ⤴
The visitor pattern is a solution of problem where you need to add operation on a class hierarchy but without touching them.
This pattern uses double dispatch to add another level of indirection.
-
When do you use Composite design pattern? ⤴
Composite design pattern arranges objects into tree structures to represent part-whole hierarchies.
It allows clients treat individual objects and container of objects uniformly.
Use Composite pattern when you want to represent part-whole hierarchies of objects.
-
The difference between Inheritance and Composition? ⤴
Though both allows code reuse, Composition is more flexible than Inheritance because it allows you to switch to another implementation at run-time.
Code written using Composition is also easier to test than code involving inheritance hierarchies.
-
What is the difference between overloading and overriding? ⤴
overloading -- adding a method with the same name but different signature
- Method overloading in Java occurs when two or more methods in the same class have the exact same name but different parameters.
- Overloading happens at compile time
overriding -- changing the method implementation in the subclass
- An overridden method would have the exact same method name, return type, number of parameters and types of parameters as the method in parent class.
- The only difference would be the definition of the method.
- Overriding happens at run time
- Inheritance is necessary for overriding.
-
Can you override a private or static method in Java? ⤴
Another popular Java tricky question, As I said method overriding is a good topic to ask trick questions in Java. Anyway, you can not override a private or static method in Java, if you create a similar method with same return type and same method arguments in child class then it will hide the super class method, this is known as method hiding. Similarly, you cannot override a private method in sub class because it's not accessible there, what you do is create another private method with the same name in the child class. See Can you override a private method in Java or more details.
-
What is meant by Inheritance and what are its advantages? ⤴
Inheritance is one of principles of OOP. It allows to create class hierarchies.
Classes can inherit methods and properties from the base classes thus increasing code reuse.
-
What is the difference between this() and super()? ⤴
- this() calls the constructor of current class.
- super() calls the superclass constructor
- super() has to be the first statement of subclass constructor;
- this and super are references to the current object and to current object treated as superclass.
- this.new Something() has to be used to create inner classes
-
What modifiers may be used with top-level class? ⤴
only public or default (package-private)
-
The difference between nested public static class and a top level class in Java? ⤴
You can have more than one nested public static class inside one class, but you can only have one top-level public class in a Java source file and its name must be same as the name of Java source file.
-
Difference between Composition, Aggregation and Association in OOP? ⤴
If two objects are related to each other, they are said to be associated with each other.
Composition and Aggregation are two forms of association in object-oriented programming.
The composition is stronger association than Aggregation.
In Composition, one object is OWNER of another object while in Aggregation one object is just USER of another object.
If an object A is composed of object B then B doesn't exist if A ceased to exists, but if object A is just an aggregation of object B then B can exists even if A ceased to exist.
-
Give me an example of design pattern which is based upon open closed principle? ⤴
This is one of the practical questions I ask experienced Java programmer. I expect them to know about OOP design principles as well as patterns.
Open closed design principle asserts that your code should be open for extension but closed for modification.
Which means if you want to add new functionality, you can add it easily using the new code but without touching already tried and tested code.
There are several design patterns which are based upon open closed design principle e.g. Strategy pattern, if you need a new strategy, just implement the interface and configure, no need to modify core logic.
One working example is Collections.sort() method which is based on Strategy pattern and follows the open-closed principle, you don't modify sort() method to sort a new object, what you do is just implement Comparator in your own way.
-
Difference between Abstract factory and Prototype design pattern? ⤴
This is the practice question for you, If you are feeling bored just reading and itching to write something, why not write the answer to this question.
I would love to see an example the, which should answer where you should use the Abstract factory pattern and where is the Prototype pattern is more suitable.
-
When do you use Flyweight pattern? ⤴
This is another popular question from the design pattern. Many Java developers with 4 to 6 years of experience know the definition but failed to give any concrete example. Since many of you might not have used this pattern, it's better to look examples from JDK. You are more likely have used them before and they are easy to remember as well. Now let's see the answer.
Flyweight pattern allows you to share object to support large numbers without actually creating too many objects. In order to use Flyweight pattern, you need to make your object Immutable so that they can be safely shared. String pool and pool of Integer and Long object in JDK are good examples of Flyweight pattern.
-
Procedural Programming vs Object-Oriented Programming ⤴
Procedural programming is a style of writing code that executes a series of linear procedures to produce a result.
Object-oriented programming is a style of writing code that uses objects to encapsulate state and behavior.
Procedural code is easier to use in small projects or in multithreaded environments due to its stateless nature, but object-oriented code is far more flexible and easier to maintain.”
-
What is the purpose of abstraction in software development? ⤴
Abstraction is the act of perceiving an entity from a narrow perspective.
For example, in the context of education a person can be reduced to a student, and in the context of employment a person can be reduced to an employee.
Each abstraction reduces the attributes of a person to a subset of relevant information. The goal of abstraction is to reduce complexity in software systems.
-
What is encapsulation? How does Java support it? ⤴
Encapsulation is a technique that encourages abstraction by purposefully hiding information.
For example, the mechanical details of a car engine are encapsulated behind a steering wheel and floor pedals. Anyone familiar with this interface could drive a car without knowing what type of engine was under the hood.
Java encourages encapsulation through the use of interfaces and by providing access modifiers that limit the visibility of classes, fields, and methods.
-
What is polymorphism? How does Java support it? ⤴
Polymorphism is a technique that encourages abstraction by allowing an entity to assume multiple forms.
For example, a smartphone is polymorphic because it can assume the role of a camera, web browser, music player, or digital clock. Each application exposes a relevant interface to the user.
In Java, an object can take on the form of any parent in its hierarchy or any interface in its hierarchy.
-
What is the difference between a mutable object and an immutable object? How can you design an object to be immutable? ⤴
Mutability refers to the ability of an entity to change its state.
An iPod is an example of a mutable entity because its contents frequently change. A vinyl record is an example of an immutable entity because its contents are permanently engraved.
Immutable objects provide numerous benefits in software applications, such as stability and thread safety. Strings and all of the primitive wrapper objects are examples of immutable objects.
In order to make an object immutable, the class must be final, all fields must be final, and it cannot expose any mutable fields or methods that modify mutable fields A Strategy for Defining Immutable Objects.
-
What is the difference between coupling and cohesion? What is the preferred relationship between software components and why? ⤴
Coupling refers to the level of dependency that exists between two entities.
For example, a cell phone battery that is soldered to a motherboard is tightly coupled because neither the battery nor the motherboard can be replaced without affecting the other component. A battery that snaps into the back of a phone is loosely coupled because both entities could be replaced independently. In software applications, decoupled components are more flexible and easier to maintain.
Cohesion refers to an entity's level of focus.
For example, a Swiss Army knife is a low cohesion entity because it can do multiple things, but it can’t do them very well. A multi-tool could never match the productivity of a toolbox filled with highly cohesive tools. In software applications, cohesive components are more robust and easier to test.
-
What is Static Binding and Dynamic Binding? ⤴
Static or early binding is resolved at compile time. Method overloading is an example of static binding.
Dynamic or late or virtual binding is resolved at run time. Method overriding is an example of dynamic binding.