Write a Java program to Static Methods and Inheritance


This Java program demonstrates the use of static methods in a class hierarchy. In this program, there are two classes: Vehicle (the parent class) and Car (the child class). Both classes have a static method named display. Static methods belong to the class rather than to instances of the class, and they can be called using the class name itself. Here's an explanation of the program:

  • public class StaticMethods: This is the main class that contains the main method, the entry point of the program.
  • public static void main(String[] args): The main method is where the program execution starts. It calls the static display method of both the Vehicle and Car classes.
  • Vehicle.display();: This line calls the static display method of the Vehicle class using the class name. The display method of the Vehicle class prints "This is a Vehicle" to the console.
  • Car.display();: This line calls the static display method of the Car class using the class name. The display method of the Car class prints "This is a Car" to the console.
  • class Vehicle: This is the parent class, which has a static method named display.
  • static void display(): The display method of the Vehicle class is a static method, and it prints "This is a Vehicle" to the console.
  • class Car extends Vehicle: This is the child class that inherits from the Vehicle class. It also has a static display method, which is separate from the one in the Vehicle class.
  • static void display(): The display method in the Car class is also a static method, and it prints "This is a Car" to the console.

This program demonstrates the use of static methods in a class hierarchy. Static methods belong to the class itself and can be called using the class name. Even though the Car class inherits from the Vehicle class, it can have its own static method with the same name, and the method invoked depends on the class in which it is called. In this case, the display method in the Car class hides the one in the Vehicle class when called using the class name.


Source Code

public class StaticMethods	// Main class
{
	public static void main(String[] args)
	{
		Vehicle.display();   // Accessing static method in parent class
		Car.display();       // Accessing static method in child class
	}
}
class Vehicle	// Parent class
{
	static void display()
	{
		System.out.println("This is a Vehicle");
	}
}
class Car extends Vehicle	// Child class
{
	static void display()
	{
		System.out.println("This is a Car");
	}
}

Output

This is a Vehicle
This is a Car