Write a Java program to Final Class and Inheritance


In this Java program, you have defined a class named FinalClass and a final class named Vehicle. A final class is a class that cannot be subclassed or extended by other classes. Here's an explanation of your program:

  • public class FinalClass: 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 creates an object of the Vehicle class and calls its start method.
  • Vehicle vehicle = new Vehicle();: This line creates an object of the Vehicle class, which is a final class. Since the Vehicle class is final, it cannot be extended or subclassed.
  • vehicle.start();: This line calls the start method on the vehicle object, which prints the message "Vehicle starting ..." to the console.
  • final class Vehicle: This is the parent class, and it is marked as final, which means it cannot be subclassed. The Vehicle class has a method named start.
  • void start(): The start method of the Vehicle class simply prints the message "Vehicle starting ..." to the console.

This program demonstrates the use of a final class. The Vehicle class is marked as final, making it impossible to create subclasses of it. This ensures that no other class can extend or inherit from the Vehicle class, making it a "leaf" class in the class hierarchy. When an object of the Vehicle class is created and its start method is called, it behaves as expected without the possibility of being overridden by any subclass.


Source Code

public class FinalClass	  // Main class
{
	public static void main(String[] args)
	{
		Vehicle vehicle = new Vehicle();
		vehicle.start();
	}
}
final class Vehicle	// Final parent class
{
	void start()
	{
		System.out.println("Vehicle starting ...");
	}
}

Output

Vehicle starting ...