Are you preparing for a Java interview and need to brush up on your knowledge of java inheritance? Inheritance is a fundamental concept in Java and many interviewers like to test your understanding of it. Our blog is here to help you get ready for those questions. We’ve put together a list of common inheritance interview questions that you might be asked in a Java developer interview.
This blog will guide you through various questions, from basic concepts to more complex scenarios involving inheritance. Whether you are new to Java or have been using it for a while, understanding inheritance is crucial. Our explanations are simple and easy to understand, making sure you can confidently answer any questions about inheritance that come your way in an interview.
Inheritance Interview Questions
In this section we’re focusing on some most commonly asked interview questions on Inheritance in java. The below listed questions are also important for the java developer interview point of view. These below list of questions are best suited for both Freshers and experienced developer.
1. What is inheritance in object-oriented programming?
Ans: Inheritance is a fundamental concept in object-oriented programming (OOP) like Java. It allows a new class to inherit properties and behaviors (fields and methods) from an existing class. In Java term, new class is know as child class and the old class that is inherited by child class is know as base class or parent class. Inheritance promotes code reusability and allows for the creation of a hierarchical relationship between classes.
2. Explain the concept of single inheritance and multiple inheritance.
Ans:
Single Inheritance: In single inheritance, a class can inherit from only one superclass. In other words we can also explain single inheritance as a Java class have only one direct parent class from which it can inherit attributes and behaviors. This helps in creating a simple and linear hierarchy of classes. This results in a linear hierarchy of classes.
Multiple Inheritance: In multiple inheritance, a class can inherit from multiple superclasses. This can lead to complex hierarchies and the “diamond problem,” where ambiguity arises when a subclass inherits from two classes with the same method names.
However, Java does not support multiple inheritance of classes, meaning a class cannot directly inherit from multiple classes. This decision was made to avoid the complications and ambiguity that can arise from conflicting method and attribute names across different superclasses.
Instead of multiple inheritance, Java uses interfaces to achieve a form of multiple inheritance.
3. How does inheritance promote code reusability in object-oriented programming?
Ans: Inheritance promotes code reusability by allowing subclasses to inherit attributes and behaviors from their super classes. This means that common functionality can be defined in a base class/super classes, and subclasses can specialize or extend this functionality as needed, without duplicating code.
4. What are base class (superclass) and derived class (subclass) in inheritance?
Ans:
Base Class (Superclass): This is the class whose attributes and methods are inherited by other classes.
Derived Class (Subclass): This is the class that inherits attributes and methods from the superclass. It can also define its own attributes and methods or override inherited ones.
5. Describe the difference between method overriding and method overloading.
Ans:
Method Overriding: Method Overriding mean, base class is implementing same method that is implemented in super class. In this case the method signatures will be the same in child class as per super class. At run time it will be decided which method will be called.
Method Overloading: This involves defining multiple methods in the same class with the same name but different parameters (different method signatures). At compile time it will be decided which method will be call.
6. What is a constructor chaining in inheritance? How is it achieved?
Ans: Constructor chaining refers to the process of calling constructors of the superclass when creating an instance of a subclass. This ensures that both the subclass and superclass constructors are executed, allowing for proper initialization of attributes in both classes.
class Parent {
private int parentValue;
public Parent() {
parentValue = 10;
}
public Parent(int value) {
parentValue = value;
}
}
public class Child extends Parent {
private int childValue;
public Child() {
super(); // Calls the default constructor of the parent class
childValue = 20;
}
public Child(int parentValue, int childValue) {
super(parentValue); // Calls the parameterized constructor of the parent class
this.childValue = childValue;
}
}
7. Explain the “is-a” relationship and how it’s related to inheritance.
Ans: The “is-a” relationship is a fundamental principle of inheritance. Here a subclass is said to be a specialized version of its superclass. For example, if you have a class hierarchy like “Vehicle” (superclass) and “Car” (subclass), you can say that a car “is-a” vehicle.
8. How does the access modifier (public, protected, private) affect inheritance?
Ans: Access modifiers (public, protected, private) control the visibility of attributes and methods. Inheritance can affect access as follows:
- Public members: Inherited and accessible any where.
- Protected members: Inherited and accessible within subclasses.
- Private members: Not inherited or accessible.
9. Discuss the diamond problem in multiple inheritance and how it can be resolved.
Ans: The diamond problem occurs in java during multiple inheritance. When a subclass inherits from two classes that have a common superclass. This can lead to ambiguity. It’s resolved in some languages by using virtual inheritance or interfaces to clarify the method implementation source.
class A {
void foo() {
System.out.println("A's foo");
}
}
class B extends A {
void foo() {
System.out.println("B's foo");
}
}
class C extends A {
void foo() {
System.out.println("C's foo");
}
}
class D extends B, C {
}
public class Main {
public static void main(String[] args) {
D d = new D();
d.foo();
}
}
In the above example, class D
is attempting to inherit from both classes B
and C
, which themselves inherit from class A
. The diamond problem occurs because D
now has two paths to the foo()
method inherited from class A
. This ambiguity leads to a compilation error because the compiler doesn’t know which version of the foo()
method to use.
In Java, the diamond problem is prevented through a mechanism called “virtual inheritance.” Java supports only single inheritance for classes, meaning a class can directly inherit from only one class. However, a class can implement multiple interfaces, which provides a form of multiple inheritance for method declarations.
10. What is the Object class in Java? How does it relate to all other classes?
Ans: In Java, the Object class is the root class for all other classes. It provides common methods like toString()
, equals()
, and hashCode()
. All classes in Java implicitly or explicitly inherit from the Object class.
11. Can a subclass access private members of its superclass? Why or why not?
Ans: A subclass cannot directly access the private members of its superclass. Private members are only accessible within the class they are defined in. Subclasses can access protected and public members.
12. What is the ‘super’ keyword used for in inheritance? Provide an example.
Ans: The super
keyword is used to refer to the superclass of the current subclass instance. It’s often used to call superclass constructors or access overridden methods.
class Subclass extends Superclass {
void someMethod() {
super.someMethod(); // Calls the overridden method in the superclass
}
}
13. Describe the concept of abstract classes and how they relate to inheritance.
Ans: Abstract class are class that cannot be instantiated on their own. They can have abstract methods (methods without implementation) that must be implemented by their subclasses. Abstract classes provide a common template for subclasses while enforcing specific method implementations.
14. Explain the concept of method visibility and access control in inheritance.
Ans: Access modifiers determine the visibility of methods in subclasses. Public and Protected methods can be inherited and accessed, while Private methods are not inherited. Subclasses can override methods with the same name and same parameter to provide different implementations.
15. How can you prevent a class from being inherited in Java?
Ans: To prevent a class from being inherited in Java, you can use the final
keyword. Declaring a class as final
makes it impossible to create subclasses.
16. Discuss the potential drawbacks or challenges of using inheritance in a software design.
Ans: Drawbacks of Inheritance:
- Tight Coupling: Inheritance can create tight coupling between classes, making changes in the superclass affect its subclasses.
- Inflexible Hierarchies: Deep inheritance hierarchies can become complex and inflexible to modify.
- Method Overhead: Inherited methods might not be relevant to subclasses, causing method bloat and overhead.
- Limited Reusability: Inheritance can lead to code duplication if subclasses share only part of the superclass’s functionality.
17. When would you prefer using composition over inheritance?
Ans: Composition involves creating a class by combining other classes as components, instead of inheriting their behaviors directly. It’s preferred when there’s no clear “is-a” relationship, to avoid issues related to deep hierarchies and promote flexibility.
Choosing Between Composition and Inheritance:
- Use inheritance when there’s a clear “is-a” relationship between the classes and you want to share behavior and structure.
- Use composition when you want to build complex objects by combining simpler components, achieving better encapsulation and flexibility.
18. Give an example of a real-world scenario where inheritance would be beneficial.
Ans: Inheritance is beneficial when there’s a clear hierarchical relationship between classes. We can take an example of GUI frameworks where different types of UI elements inherit from a common base class and sharing core functionality while specializing behavior.
One more real-world scenario it there which is modeling different types of vehicles in a transportation system.
class Vehicle {
private String manufacturer;
private int year;
public Vehicle(String manufacturer, int year) {
this.manufacturer = manufacturer;
this.year = year;
}
public void startEngine() {
System.out.println("Engine started.");
}
public void stopEngine() {
System.out.println("Engine stopped.");
}
}
class Car extends Vehicle {
private int numberOfSeats;
public Car(String manufacturer, int year, int numberOfSeats) {
super(manufacturer, year);
this.numberOfSeats = numberOfSeats;
}
public void drive() {
System.out.println("Car is being driven.");
}
}
class Bicycle extends Vehicle {
private int numberOfGears;
public Bicycle(String manufacturer, int year, int numberOfGears)
{
super(manufacturer, year);
this.numberOfGears = numberOfGears;
}
public void pedal() {
System.out.println("Bicycle is being pedaled.");
}
}
In this scenario, the Vehicle
class serves as the base class, providing common attributes and methods that all types of vehicles share. The Car
and Bicycle
classes are subclasses that inherit from the Vehicle
class. They can add their specific attributes and methods while reusing the common behaviors provided by the superclass.
19. What happens if a subclass has a method with the same name as the one in its superclass?
Ans: If a subclass has a method with the same name as a method in its superclass, it’s said to be overriding the method. The subclass’s method implementation will be used instead of the superclass’s method when called on instances of the subclass.
20. Explain the term “method hiding” and how it’s related to static methods and inheritance.
Ans: Method hiding occurs when a subclass defines a static method with the same signature as a static method in its superclass. When you call the static method using the subclass reference, the method in the subclass is invoked, even if the object’s actual type is a superclass. This behavior is different from instance methods, where the method to be called is determined at runtime based on the actual object’s type
class A {
static void staticMethod() {
System.out.println("Static method in class A");
}
}
class B extends A {
static void staticMethod() {
System.out.println("Static method in class B");
}
}
public class Main {
public static void main(String[] args) {
A a = new B();
a.staticMethod();
}
}
Output
Static method in class A
In this example, even though the reference a
points to an instance of class B
, the static method from class A
is called because static methods are determined at compile time based on the reference type (A
), not the actual object type (B
).
21. In the context of Java, what is the significance of the final
keyword in relation to inheritance?
Ans: The final
keyword can be used to prevent a class from being subclassed. When a class is declared as final
, it cannot be extended by any other class.
22. What is a shallow copy and a deep copy when dealing with inheritance and objects?
Ans:
Shallow Copy: Creating a copy of an object that contains references to the same objects as the original. Changes in the copied object’s referenced objects are reflected in both the original and the copy.
Example:
class Person {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Shallow copy constructor
public Person(Person other) {
this.name = other.name;
this.address = other.address;
}
public Address getAddress(){
return this.address;
}
}
class Address {
private String city;
public Address(String city) {
this.city = city;
}
}
public class Main {
public static void main(String[] args) {
Address address = new Address("New York");
Person person1 = new Person("Alice", address);
// Shallow copy
Person person2 = new Person(person1);
System.out.println(person1 == person2);
System.out.println(person1.getAddress() == person2.getAddress());
System.out.println(person1.getAddress())
System.out.println(person2.getAddress());
}
}
Output
false
true
Address@1e81f4dc
Address@1e81f4dc
Deep Copy: Creating a copy of an object that also involves copying all the objects referenced by the original object. Changes in the copied object’s referenced objects do not affect the original or the copy.
class Person {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
// Deep copy constructor
public Person(Person other) {
this.name = other.name;
this.address = new Address(other.address);
}
public Address getAddress(){
return this.address;
}
}
class Address {
private String city;
public Address(String city) {
this.city = city;
}
// Deep copy constructor
public Address(Address other) {
this.city = other.city;
}
}
public class Main {
public static void main(String[] args) {
Address address = new Address("New York");
Person person1 = new Person("Alice", address);
// Deep copy
Person person2 = new Person(person1);
System.out.println(person1 == person2); // false
System.out.println(person1.getAddress() == person2.getAddress()); // false (deep copy)
System.out.println(person1.getAddress());
System.out.println(person2.getAddress());
}
}
Output
false
false
Address@1e81f4dc
Address@4d591d15