简体   繁体   中英

How do I override a method

    class TestTax {
    public static void main (String[] args){
        NJTax t = new NJTax();

        t.grossIncome= 50000;
        t.dependents= 2;
        t.state= "NJ";

        double yourTax = t.calcTax();
        double totalTax = t.adjustForStudents(yourTax);

        System.out.println("Your tax is " + yourTax);
    }
}

    class tax {
    double grossIncome;
    String state;
    int dependents;

    public double calcTax(){
        double stateTax = 0;
        if(grossIncome < 30000){
            stateTax = grossIncome * 0.05;
        }
        else{
            stateTax = grossIncome * 0.06;
        }
        return stateTax;
    }

    public void printAnnualTaxReturn(){
        // code goes here
    }
}



    public class NJTax extends tax{
    double adjustForStudents (double stateTax){
    double adjustedTax = stateTax - 500;
    return adjustedTax;

        public double calcTax(){

        }

    }
}

I am having trouble with the Lesson requirement to: "Change the functionality of calcTax( ) by overriding it in NJTax. The new version of calcTax( ) should lower the tax by $500 before returning the value."

How is this accomplished. I just have safaribooksonline and no videos for the solution.

http://download.oracle.com/javase/tutorial/java/IandI/override.html

Class names should start with a capital letter as well. Since I'm not exactly sure what you wanted regarding functionality, here's just an example. Super refers to the parent class, in this case being tax . Thus, NJTax 's calcTax() method returns tax.calcTax() - 500 . You also may want to look into using the @Override annotation as a way of making it clear that a method is being overridden and to provide a compile-time check.

public class NJTax extends tax {

    public double adjustForStudents (double stateTax) {
        double adjustedTax = stateTax - 500;
        return adjustedTax;
    }

    public double calcTax() {
        return super.calcTax() - 500;
    }

}
public class NJTax extends tax{

    double adjustForStudents (double stateTax){
       double adjustedTax = stateTax - 500;
       return adjustedTax;
    }

    public double calcTax(){
       double stateTax = super.calcTax();
       return this.adjustforStudents(stateTax);
    }

}

hint: return the same value as tax.calcTax() minus $500.

For overriding you base class (Tax) implementation of calcTax, just add your own implementation of calcTax in NJTax. This could be as simple as

public double calcTax(){
   return super.calcTax() -500;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM