Java MCQ: What is the parent class of all classes in Java?
Answer:
Explanation:
In Java, the Object
class is the root of the class hierarchy. Every class in Java, either directly or indirectly, inherits from the Object
class. This means that the Object
class provides a set of methods that are available to all Java objects, regardless of the specific class they belong to.
Some of the most commonly used methods from the Object
class include equals()
, hashCode()
, toString()
, and clone()
. These methods are often overridden in subclasses to provide class-specific behavior. For example, the toString()
method is frequently overridden to return a string representation of an object, which is useful for debugging and logging:
class Car {
String model;
Car(String model) {
this.model = model;
}
@Override
public String toString() {
return "Car model: " + model;
}
}
Car car = new Car("Toyota");
System.out.println(car); // Outputs: Car model: Toyota
In this example, the toString()
method is overridden in the Car
class to return a more meaningful representation of the object. Understanding that Object
is the parent class of all classes in Java is essential because it highlights the shared capabilities and common functionality that all objects in Java possess. This also enables developers to use polymorphism and type hierarchies effectively in their code.