I wrote Java code using abstraction to calculate federal and state income tax from a salary.
The code is below.
import java.util.Scanner;
abstract class USA_Tax{
protected final double income_tax = 0.15;
protected double pre_tax_amount;
protected double tax_to_fed;
public void federal_tax(){
Scanner input = new Scanner (System.in);
System.out.println ("Enter pre-tax income: ");
double pre_tax_amount = input.nextDouble();
System.out.println ("Money owned to federal government: ");
tax_to_fed = (double)(pre_tax_amount*0.15);
System.out.println (tax_to_fed);
input.close();
}
}
class California_Tax extends USA_Tax{
protected final double ca_income_tax = 0.10;
protected double after_california_tax;
protected double total_money_left;
public void ca_tax(){
after_california_tax = (double)(pre_tax_amount * ca_income_tax);
System.out.println("Money owned to CA government: " + after_california_tax);
total_money_left = (pre_tax_amount) - (after_california_tax + tax_to_fed);
System.out.println ("Total take home:" + total_money_left);
}
}
public class class_abstraction{
public static void main (String[] args){
California_Tax tax1 = new California_Tax();
tax1.federal_tax();
tax1.ca_tax();
}
}
When I run the code, only values from the abstract class seem to pop up correctly. The values for the after_california_tax and total_money_left variables in the extended class show up as 0.0. Below is an example output.
Enter pre-tax income:
100000
Money owned to federal government:
15000.0
Money owned to CA government: 0.0
Total take home:-15000.0
I also tried to remove 'abstract' from the first class but nothing changed.
What am I doing wrong?
This is where you have messed up, you have created a new local variable which was not required, use the instance variable instead which you have defined.
double pre_tax_amount = input.nextDouble();
Code after the change is done
import java.util.Scanner;
abstract class USA_Tax{
protected final double income_tax = 0.15;
protected double pre_tax_amount;
protected double tax_to_fed;
public void federal_tax(){
Scanner input = new Scanner (System.in);
System.out.println ("Enter pre-tax income: ");
pre_tax_amount = input.nextDouble();
System.out.println ("Money owned to federal government: ");
tax_to_fed = (double)(pre_tax_amount*0.15);
System.out.println (tax_to_fed);
input.close();
}
}
class California_Tax extends USA_Tax{
protected final double ca_income_tax = 0.10;
protected double after_california_tax;
protected double total_money_left;
public void ca_tax(){
after_california_tax = (double)(pre_tax_amount * ca_income_tax);
System.out.println("Money owned to CA government: " + after_california_tax);
total_money_left = (pre_tax_amount) - (after_california_tax + tax_to_fed);
System.out.println ("Total take home:" + total_money_left);
}
}
public class test{
public static void main (String[] args){
California_Tax tax1 = new California_Tax();
tax1.federal_tax();
tax1.ca_tax();
}
}