public class Animal { public void makeSound() { System.out.println("Animal is making a sound"); } } public class Dog extends Animal { @Override public void makeSound() { System.out.println("Dog is barking"); } } public class Main { public static void main(String[] args) { Dog dog = new Dog(); Class superClass = dog.getClass().getSuperclass(); System.out.println("The superclass of Dog is: " + superClass.getName()); } } Output: The superclass of Dog is: Animal
public class Car { } public class BMW extends Car { } public class Main { public static void main(String[] args) { BMW bmw = new BMW(); Class superClass = bmw.getClass().getSuperclass(); System.out.println("The superclass of BMW is: " + superClass.getName()); } } Output: The superclass of BMW is: CarIn this example, we have a parent class called Car and a child class called BMW. We create an object of the BMW class and then use the getSuperclass() method to retrieve its parent class. The output shows that the superclass of BMW is Car. Package library: The getSuperclass() method is a part of the java.lang package in Java. This package is automatically imported into all Java programs and provides the fundamental classes and interfaces that support basic Java programming.