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
- Create a parent class
Govtwith a methodtax()that calculates a flat 10% tax on income. - Create a child class
NewGovtthat extendsGovt. - Override the
tax()method in the child class to calculate a complex tax (5% income tax + 20% GST + 2% surcharges + 5% bank fees). - 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
Govtclass (which might break older software relying on it). - Instead, we extend it to create
NewGovtand 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)