Discuss / Java / java static

java static

Topic source
沿用着salary那个来,增加一个static计数

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 34 };
        int[] arr1 = new int[] { 1, 2, 34 };
        System.out.println(Arrays.toString(arr) == Arrays.toString(arr1));
        Income[] incomes = new Income[] { new Salary(7120), new StateCouncilSpecialAllowance(2570) };

        System.out.println(totalTex(incomes));
        Salary s = new Salary(3000);
        System.out.println(s.getNum());
        StateCouncilSpecialAllowance ss = new StateCouncilSpecialAllowance(2500);
        StateCouncilSpecialAllowance.setNum();
        StateCouncilSpecialAllowance.setNum();
        System.out.println(ss.getNum());
        System.out.println(s.getNum());
    }

    public static double totalTex(Income... incomes) {
        double total = 0;
        for (Income income : incomes) {
            total += income.getTax();
        }
        return total;
    }
}

interface Income {

    double getTax();
}

class Salary implements Income {
    protected double income;
    public static int num = 0; //初始为0

    public Salary(double income) {
        this.income = income;
    }

    public double getTax() {
        if (income > 5000) {
            return (income - 5000) * 0.2;
        } else {
            return 0;
        }
    }

    public int getNum() {
        return this.num;
    }
}

class StateCouncilSpecialAllowance extends Salary {

    public StateCouncilSpecialAllowance(double income) {
        super(income);
    }

    public double getTax() {
        return 0;
    }

    public static void setNum() { //调用一次加1
        num += 1;
    }
}

num++应该写在构造方法里面才对;

这里的写法成了统计setNum调用次数了


  • 1

Reply