Skip to main content

ProwessApps

Learn · Practice · Excel

Create a class Govt which has method to calculate the Tax(10 %). Override the method tax() in derived classNewGovt and display the tax.

Java Code Example — Polymorphism Programs

ADVERTISEMENT

Create a class Govt which has method to calculate the Tax(10 %). Override the method tax() in derived classNewGovt and display the tax.

Objective

Write a Java program to calculate Government Tax using Method Overriding.

Algorithm / Approach

  1. Create a parent class Govt with a method tax() that calculates a flat 10% tax on income.
  2. Create a child class NewGovt that extends Govt.
  3. Override the tax() method in the child class to calculate a complex tax (5% income tax + 20% GST + 2% surcharges + 5% bank fees).
  4. In main, execute both methods to compare the old tax system versus the new tax system.
Govt.java
import java.util.Scanner;
class Govt {
 double income;
 double tax;
 void input() {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Income: ");
  income = s.nextDouble();
 }
 void tax() {
  tax = 0.1*income;
  System.out.println("Tax = "+tax);
 }
}
class NewGovt extends Govt{
 void tax() {
  double in =income*0.05;
  double gst =income*0.2;
  double si =income*0.02;
  double bank =income*0.05;
  tax=in+gst+si+bank;
  System.out.println("Tax = "+tax);
 }
}
class Main {
 public static void main(String[] a)
 {
  Govt c = new Govt();
  System.out.println("Govt Method");
  c.input();
  c.tax();
  System.out.println("NewGovt Method");
  NewGovt ng = new NewGovt();
  ng.input();
  ng.tax();
 }
}

Expected Output

Govt Method
Enter Income: 500000
Tax = 50000.0
NewGovt Method
Enter Income: 500000
Tax = 160000.0

Explanation of the Program

  • This program shows how business logic can evolve using OOP principles.
  • When a new government comes into power with a new tax plan, we don't delete or modify the old Govt class (which might break older software relying on it).
  • Instead, we extend it to create NewGovt and override the specific behavior that changed. This is the Open/Closed Principle: software entities should be open for extension, but closed for modification.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT