Question
How can I use a superclass to initialize a subclass object in Java?
class Superclass {
void display() {
System.out.println("This is a superclass method.");
}
}
class Subclass extends Superclass {
void display() {
System.out.println("This is a subclass method.");
}
}
public class Main {
public static void main(String[] args) {
Superclass obj = new Subclass();
obj.display(); // Calls the subclass method
}
}
Answer
In Java, initializing a subclass object using a superclass reference is a common practice that allows for polymorphism, enabling method overriding and dynamic method dispatch.
class Animal {
void sound() {
System.out.println("Animal makes a sound.");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows.");
}
}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound(); // Outputs: Dog barks.
myCat.sound(); // Outputs: Cat meows.
}
}
Causes
- Understanding inheritance in Java
- Need for polymorphic behavior in applications
- Desire to treat objects of different classes similarly
Solutions
- Use a superclass type reference to hold a subclass object.
- Override methods in the subclass to provide specific implementations.
- Call the overridden methods using the superclass reference.
Common Mistakes
Mistake: Confusing the superclass and subclass references
Solution: Always ensure that you use the correct reference type to avoid compilation errors.
Mistake: Failing to override methods in the subclass
Solution: Make sure to implement the overridden methods in the subclass to achieve polymorphic behavior.
Helpers
- Java superclass
- initialize subclass object Java
- Java inheritance
- polymorphism in Java
- Java method overriding