Unit3 - Subjective Questions
CSE310 • Practice Questions with Detailed Answers
Define Inheritance in Java. Explain the different types of inheritance supported by Java with suitable diagrams or descriptions.
Definition: Inheritance is a mechanism in which one object acquires all the properties and behaviors of a parent object. It represents the IS-A relationship (parent-child relationship). It is used for code reusability and method overriding.
Types of Inheritance supported in Java:
- Single Inheritance: A class inherits another class. (Class B extends Class A).
- Multilevel Inheritance: There is a chain of inheritance. (Class C extends Class B, which extends Class A).
- Hierarchical Inheritance: Two or more classes inherit the same class. (Class B extends A and Class C extends A).
Note: Java does not support Multiple Inheritance (one class extending multiple classes) through classes to avoid the Diamond Problem, but it is supported through Interfaces.
What is Method Overriding? List the rules that must be followed while overriding a method in Java.
Method Overriding occurs when a subclass (child class) has the same method as the parent class.
Rules for Method Overriding:
- Same Name: The method name must be exactly the same as in the parent class.
- Same Parameters: The argument list must be exactly the same as in the parent class.
- IS-A Relationship: There must be an inheritance relationship.
- Access Modifier: The access modifier of the overriding method cannot be more restrictive than the overridden method of the parent class (e.g., if the parent is
protected, the child cannot beprivate). - Exception Handling: The overriding method can throw any unchecked exceptions, but cannot throw new or broader checked exceptions than those declared by the overridden method.
- Return Type: The return type must be the same or a covariant type (a subclass of the return type declared in the parent class).
Explain the usage of the super keyword in Java with examples. How is it used to invoke parent class constructors?
The super keyword is a reference variable that is used to refer to the immediate parent class object.
Uses:
-
Refer Immediate Parent Class Instance Variable: Used when the parent and child classes have members with the same name.
java
System.out.println(super.color); -
Invoke Immediate Parent Class Method: Used if the method is overridden in the child class.
java
super.eat(); -
Invoke Immediate Parent Class Constructor:
super()is used to invoke the parent class constructor. It must be the first statement in the child class constructor.
java
class Child extends Parent {
Child() {
super(); // Calls Parent() constructor
System.out.println("Child Created");
}
}
Differentiate between Method Overloading and Method Overriding in Java.
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Definition | Same method name with different parameters in the same class. | Same method name and parameters in a subclass. |
| Polymorphism | Compile-time polymorphism (Static Binding). | Runtime polymorphism (Dynamic Binding). |
| Return Type | Can be same or different. | Must be same or covariant. |
| Method Signature | Must be different (number or type of args). | Must be same. |
| Keywords | No specific keyword needed. | @Override annotation is recommended but not mandatory. |
| Inheritance | Not required. | Required. |
Explain the significance of the Object class in Java. Why do we override the toString() and equals() methods?
The Object class is the root of the class hierarchy. Every class in Java has Object as a superclass (directly or indirectly).
Significance of overriding:
-
toString()method:- Default behavior: Returns the class name followed by the "@" symbol and the unsigned hexadecimal representation of the object's hash code.
- Reason to override: To provide a meaningful string representation of the object (e.g., printing the values of variables) when passed to
System.out.println.
-
equals()method:- Default behavior: Compares object references (memory addresses), similar to
==. - Reason to override: To compare the content or state of two objects (logical equality) rather than their memory locations.
- Default behavior: Compares object references (memory addresses), similar to
Discuss the final keyword in Java. Explain its effect when applied to a variable, a method, and a class.
The final keyword is used to restrict the user.
-
Final Variable:
- When applied to a variable, its value cannot be changed once initialized.
- It essentially becomes a constant.
- Example:
final int MAX_SPEED = 100;
-
Final Method:
- When applied to a method, it cannot be overridden by a subclass.
- It ensures the implementation remains consistent.
- Example:
final void run() { ... }
-
Final Class:
- When applied to a class, it cannot be extended (inherited).
- It prevents inheritance entirely.
- Example:
final class String { ... }
What is Dynamic Method Dispatch (Runtime Polymorphism)? Demonstrate it with a code example.
Dynamic Method Dispatch is the mechanism by which a call to an overridden method is resolved at runtime rather than compile-time. This occurs when a reference variable of a Parent class refers to an object of the Child class.
Example:
java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog Barks");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Cat Meows");
}
}
public class TestPolymorphism {
public static void main(String args[]) {
Animal a; // Reference of type Animal
a = new Dog(); // Object of Dog
a.sound(); // Output: Dog Barks (Resolved at runtime)
a = new Cat(); // Object of Cat
a.sound(); // Output: Cat Meows
}
}
Here, the method called depends on the actual object a is referring to, not the type of the reference variable.
Define an Abstract Class. How does it differ from a concrete class? Provide a syntax example.
Abstract Class: A class that is declared with the abstract keyword. It may have abstract methods (methods without a body) as well as concrete methods (methods with a body).
Differences from Concrete Class:
- Instantiation: An abstract class cannot be instantiated (you cannot create an object of it using
new). - Methods: It can contain abstract methods, which must be implemented by the subclass (unless the subclass is also abstract).
- Purpose: It acts as a template for other classes.
Syntax:
java
abstract class Shape {
abstract void draw(); // Abstract method
void info() { // Concrete method
System.out.println("This is a shape.");
}
}
What is an Interface in Java? Explain its syntax and how it supports multiple inheritance.
Interface: An interface in Java is a blueprint of a class. It is a collection of abstract methods (before Java 8) and static constants. It is used to achieve 100% abstraction and multiple inheritance.
Syntax:
java
interface Printable {
void print();
}
Supporting Multiple Inheritance:
Java classes cannot extend multiple classes, but they can implement multiple interfaces. Since interfaces do not hold the state (instance variables) or implementation details (prior to Java 8 default methods, and even then, Diamond problem is resolved explicitly), ambiguity is avoided.
Example: class A implements Interface1, Interface2 { ... }
Compare and contrast Abstract Classes and Interfaces in Java.
| Feature | Abstract Class | Interface |
|---|---|---|
| Keyword | abstract keyword used. |
interface keyword used. |
| Methods | Can have abstract and non-abstract (concrete) methods. | Can only have abstract methods (Java 8 added default/static methods). |
| Variables | Can have final, non-final, static, and non-static variables. | Variables are implicitly public static final. |
| Inheritance | A class can extend only one abstract class. | A class can implement multiple interfaces. |
| Constructors | Can have constructors. | Cannot have constructors. |
| Access Modifiers | Members can have protected, public, etc. |
Members are implicitly public. |
| Usage | Use when related classes share some common code. | Use to define a contract for unrelated classes or achieve multiple inheritance. |
What is the instanceof operator? Explain its purpose with a code snippet.
The instanceof operator is a comparison operator used to test whether the object is an instance of a specified type (class, subclass, or interface). It returns true or false.
Purpose:
It is mainly used for downcasting safely to avoid ClassCastException.
Code Snippet:
java
class Animal {}
class Dog extends Animal {}
public class Test {
public static void main(String args[]) {
Animal a = new Dog();
if (a instanceof Dog) {
System.out.println("a is an instance of Dog");
Dog d = (Dog)a; // Safe downcasting
}
}
}
Elaborate on the concepts of Default and Static methods in Interfaces introduced in Java 8.
Java 8 introduced the ability to have method implementations inside interfaces.
1. Default Methods:
- Defined using the
defaultkeyword. - Purpose: To allow adding new methods to interfaces without breaking the classes that implement them (Backward Compatibility).
- Overriding: Implementing classes can override them or use the default implementation.
java
interface MyInterface {
default void show() {
System.out.println("Default Method");
}
}
2. Static Methods:
- Defined using the
statickeyword. - Purpose: To define utility methods associated with the interface.
- Calling: They cannot be overridden and are called using the interface name.
java
interface MyInterface {
static void info() {
System.out.println("Utility Method");
}
}
// Call: MyInterface.info();
Can constructors be inherited? Explain the constructor chaining mechanism in inheritance.
Can constructors be inherited?
No, constructors are not inherited by the subclass. However, the constructor of the superclass is invoked when the subclass is instantiated.
Constructor Chaining:
When an object of a subclass is created, the subclass constructor is called. Before executing the body of the subclass constructor, it implicitly calls the superclass constructor (using super()), ensuring that the parent object is initialized first. This process continues up to the Object class.
Order of Execution:
- Parent Constructor (executed first).
- Child Constructor (executed last).
Write a Java program to calculate the area of a Rectangle and a Circle using an abstract class Shape.
java
abstract class Shape {
abstract void area();
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
void area() {
System.out.println("Area of Rectangle: " + (length * width));
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
void area() {
System.out.println("Area of Circle: " + (Math.PI * radius * radius));
}
}
public class Main {
public static void main(String args[]) {
Shape s1 = new Rectangle(10, 5);
Shape s2 = new Circle(7);
s1.area();
s2.area();
}
}
Explain the concept of Covariant Return Type with respect to method overriding.
Before Java 5, the return type of the overriding method had to be exactly the same as the overridden method. Java 5 introduced Covariant Return Types.
Concept:
It allows the overriding method to have a return type that is a subclass of the return type declared in the overridden method in the parent class.
Example:
java
class A {
A get() {
return this;
}
}
class B extends A {
@Override
B get() { // Covariant Return Type: B is a subclass of A
return this;
}
}
This helps in avoiding type casting in the client code.
Can we declare an interface as final? Explain why or why not.
No, we cannot declare an interface as final.
Reason:
- The
finalkeyword prevents a class from being inherited (extended) or a method from being overridden. - The primary purpose of an
interfaceis to be implemented by classes. It is inherently abstract. - If an interface were marked
final, no class could implement it, rendering the interface useless. - Therefore, the combination of
interfaceandfinalis illegal and leads to a compile-time error.
What happens if a class implements two interfaces that have a default method with the same name and signature? How is this resolved?
This situation creates a conflict known as the Diamond Problem in interfaces.
What happens:
The compiler will throw an error because it doesn't know which default implementation to use.
Resolution:
The implementing class must override the conflicting method to resolve the ambiguity. Inside the overridden method, the developer can choose to call a specific interface's implementation using super.
Syntax:
java
interface A { default void show() { ... } }
interface B { default void show() { ... } }
class C implements A, B {
public void show() {
A.super.show(); // Calls A's version
// OR provide logic completely
}
}
Write a Java program to demonstrate the use of super to access a hidden field in the superclass.
When a subclass declares a variable with the same name as one in the superclass, the subclass variable hides the superclass variable. super is used to access the hidden variable.
java
class Parent {
int num = 100;
}
class Child extends Parent {
int num = 200;
void display() {
System.out.println("Child num: " + num); // Prints 200
System.out.println("Parent num: " + super.num); // Prints 100
}
}
public class Test {
public static void main(String[] args) {
Child c = new Child();
c.display();
}
}
Discuss the visibility of methods during overriding. Can we reduce the visibility of an inherited method?
Visibility Rule:
When overriding a method, the access level cannot be more restrictive than the overridden method's access level. However, it can be less restrictive (more visible).
Order of Restriction:
private > default (package-private) > protected > public
Examples:
- If Parent is
public, Child must bepublic. - If Parent is
protected, Child can beprotectedorpublic. - If Parent is
default, Child can bedefault,protected, orpublic.
Why?
This ensures that an instance of the Child class can seamlessly replace an instance of the Parent class (Liskov Substitution Principle) without access errors.
How does Java support inheritance between interfaces? Explain with syntax.
In Java, an interface can inherit from another interface using the extends keyword. Unlike classes, an interface can extend multiple interfaces.
Syntax:
java
interface A {
void methodA();
}
interface B {
void methodB();
}
// Interface C inherits from both A and B
interface C extends A, B {
void methodC();
}
class MyClass implements C {
// Must implement methodA(), methodB(), and methodC()
}
This allows for building complex hierarchies of abstractions.