开发者

How do I override a method

开发者 https://www.devze.com 2023-03-12 04:55 出处:网络
class TestTax { public static void main (String[] args){ NJTax t = new NJTax(); t.grossIncome= 50000; t.dependents= 2;
    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 开发者_Python百科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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消