Object Oriented Programming In Java Interview Questions
Comprehensive object oriented programming in java interview questions and answers for Java. Prepare for your next job interview with expert guidance.
Questions Overview
1. What are the four main principles of Object-Oriented Programming? Explain how Java implements each one.
Basic2. What is the difference between an abstract class and an interface in Java?
Basic3. Explain the concept of method overriding and the role of @Override annotation.
Basic4. What is the 'super' keyword in Java and when is it used?
Basic5. How does encapsulation contribute to data hiding and what are its benefits?
Moderate6. What is the difference between composition and inheritance? When should each be used?
Moderate7. Explain the concept of method binding and the difference between static and dynamic binding.
Advanced8. What are marker interfaces in Java? Provide examples and explain their significance.
Moderate9. How does the singleton pattern work in Java and what are its limitations?
Advanced10. What is the Liskov Substitution Principle? How does it relate to inheritance in Java?
Advanced11. How do inner classes work in Java and what are their types?
Moderate12. Explain the concept of object cloning in Java and its implications.
Advanced13. What is the diamond problem in multiple inheritance and how does Java address it?
Advanced14. How does the instanceof operator work with inheritance hierarchies?
Moderate15. What are sealed classes in Java and how do they affect inheritance?
Advanced16. How does method dispatch work in Java when dealing with overloaded and overridden methods?
Advanced17. What is the role of constructors in inheritance and object creation?
Basic18. How do abstract methods differ from default methods in interfaces?
Moderate19. What are the SOLID principles and how are they implemented in Java?
Advanced20. Explain the concept of cohesion and coupling in OOP and their importance.
Advanced1. What are the four main principles of Object-Oriented Programming? Explain how Java implements each one.
BasicThe four main principles are: 1) Encapsulation: implemented through access modifiers (private, protected, public) and getter/setter methods, 2) Inheritance: achieved using 'extends' keyword for class inheritance and 'implements' for interfaces, 3) Polymorphism: supported through method overriding and method overloading, 4) Abstraction: implemented using abstract classes and interfaces.
2. What is the difference between an abstract class and an interface in Java?
BasicAbstract classes can have both abstract and concrete methods, instance variables, constructors, and can provide default method implementations. Interfaces (before Java 8) could only have abstract methods and constants. Since Java 8, interfaces can have default and static methods, and since Java 9, private methods. A class can implement multiple interfaces but extend only one abstract class.
3. Explain the concept of method overriding and the role of @Override annotation.
BasicMethod overriding occurs when a subclass provides a specific implementation of a method declared in its superclass. The method must have the same signature and a return type that is covariant with the parent's return type. The @Override annotation helps catch errors by ensuring the method actually overrides a superclass method. It's a good practice to always use @Override when intending to override methods.
4. What is the 'super' keyword in Java and when is it used?
BasicThe 'super' keyword refers to the parent class object. It's used to: 1) Call parent class constructor (super()), 2) Access parent class methods when overridden in child class (super.methodName()), 3) Access parent class fields when hidden by child class fields. It must be the first statement in constructor if used for constructor calling.
5. How does encapsulation contribute to data hiding and what are its benefits?
ModerateEncapsulation combines data and methods that operate on that data within a single unit (class) and restricts access to internal details. Benefits include: 1) Better control over data access and modification, 2) Ability to change implementation without affecting code using the class, 3) Prevention of unauthorized access, 4) Support for validation when setting values. Implemented using private fields with public getter/setter methods.
6. What is the difference between composition and inheritance? When should each be used?
ModerateComposition creates a 'has-a' relationship where one class contains objects of another class. Inheritance creates an 'is-a' relationship where one class is a specialized version of another. Composition is preferred when you want to reuse code without creating tight coupling, more flexible for runtime behavior changes, and follows 'favor composition over inheritance' principle. Inheritance is appropriate when subclass is truly a specialized version of superclass.
7. Explain the concept of method binding and the difference between static and dynamic binding.
AdvancedMethod binding is the process of linking a method call to its definition. Static binding (compile-time) occurs with private, static, and final methods where the compiler knows which method to call. Dynamic binding (runtime) occurs with virtual methods that can be overridden, where the actual object type determines which method is called. Dynamic binding enables polymorphism in Java.
8. What are marker interfaces in Java? Provide examples and explain their significance.
ModerateMarker interfaces are empty interfaces used to mark or tag a class as having certain properties (e.g., Serializable, Cloneable). They don't contain methods but provide runtime type information through instanceof operator. While annotations now provide similar functionality, marker interfaces have advantages: compile-time type checking and the ability to create type hierarchies.
9. How does the singleton pattern work in Java and what are its limitations?
AdvancedSingleton ensures a class has only one instance and provides global access to it. Implemented using private constructor and static instance method. Limitations include: making unit testing difficult, potentially violating single responsibility principle, creating global state, and threading issues. Modern alternatives include dependency injection and proper object lifecycle management.
10. What is the Liskov Substitution Principle? How does it relate to inheritance in Java?
AdvancedThe Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of its subclasses without affecting program correctness. In Java, this means subclass methods should: accept parameters of same/wider types, return same/narrower types, throw same/fewer exceptions, and maintain superclass invariants. Violations indicate poor inheritance hierarchy design.
11. How do inner classes work in Java and what are their types?
ModerateJava supports four types of inner classes: 1) Regular inner classes (non-static nested classes) with access to outer class members, 2) Static nested classes without outer class instance access, 3) Local classes defined in methods, 4) Anonymous classes for one-time use. Inner classes can access private members of outer class and are useful for encapsulation and callback implementations.
12. Explain the concept of object cloning in Java and its implications.
AdvancedObject cloning creates a copy of an object using the clone() method from Object class. Classes must implement Cloneable interface and override clone(). Shallow cloning copies object references, while deep cloning creates new instances of referenced objects. Considerations include: handling circular references, maintaining invariants, and dealing with final fields. Alternative approaches include copy constructors or static factory methods.
13. What is the diamond problem in multiple inheritance and how does Java address it?
AdvancedThe diamond problem occurs in multiple inheritance when a class inherits from two classes that have a common ancestor, creating ambiguity about which version of inherited methods to use. Java avoids this by not supporting multiple class inheritance, only allowing multiple interface inheritance. With interfaces, the most specific default method implementation is used, or compilation fails if ambiguous.
14. How does the instanceof operator work with inheritance hierarchies?
ModerateThe instanceof operator checks if an object is an instance of a class, superclass, or interface. It returns true for any class in the inheritance chain or implemented interfaces. Since Java 16, pattern matching with instanceof allows direct casting and variable declaration. Useful for type-safe downcasting but overuse can indicate poor design or violation of polymorphism principles.
15. What are sealed classes in Java and how do they affect inheritance?
AdvancedSealed classes (Java 17+) restrict which classes can inherit from them using 'permits' clause. They provide more control over class hierarchy, ensuring only intended subclasses exist. Subclasses must be declared 'final', 'sealed', or 'non-sealed'. Useful for domain modeling, API design, and pattern matching exhaustiveness checking.
16. How does method dispatch work in Java when dealing with overloaded and overridden methods?
AdvancedMethod dispatch determines which method implementation to call. For overloaded methods, selection is based on compile-time types of arguments (static dispatch). For overridden methods, selection is based on runtime type of object (dynamic dispatch). Understanding this is crucial for polymorphic behavior and avoiding subtle bugs with method resolution.
17. What is the role of constructors in inheritance and object creation?
BasicConstructors initialize object state during creation. In inheritance, superclass constructors are called before subclass constructors. If no constructor is defined, Java provides default no-arg constructor. Constructor chaining using this() and super() must follow specific rules: can't call both in same constructor, must be first statement. Proper constructor design is crucial for object initialization and invariant maintenance.
18. How do abstract methods differ from default methods in interfaces?
ModerateAbstract methods in interfaces declare method signatures without implementation, requiring implementing classes to provide implementation. Default methods (Java 8+) provide default implementation in interfaces, allowing interface evolution without breaking existing implementations. Default methods can be overridden, and conflicts must be resolved when implementing multiple interfaces.
19. What are the SOLID principles and how are they implemented in Java?
AdvancedSOLID principles are: Single Responsibility (classes have one reason to change), Open-Closed (open for extension, closed for modification), Liskov Substitution (subtypes must be substitutable), Interface Segregation (clients shouldn't depend on unused methods), Dependency Inversion (depend on abstractions). Implementation involves proper interface design, inheritance hierarchies, and dependency management.
20. Explain the concept of cohesion and coupling in OOP and their importance.
AdvancedCohesion measures how strongly related and focused the responsibilities of a class are. Coupling measures the degree of interdependence between classes. High cohesion (class does one thing well) and loose coupling (minimal dependencies) are desired. Achieved through proper encapsulation, interface-based design, and dependency injection. Important for maintainability and reusability.