Discuss / Java / 作业问题

作业问题

Topic source

空森森森_

#1 Created at ... [Delete] [Delete and Lock User]

为什么totalTax得是static方法

Andy17861

#2 Created at ... [Delete] [Delete and Lock User]

如果不是static静态方法的话,在main中调用的时候就需要创建类对象,这样增加代码量吧,我这样理解的,main是静态方法,在不需要创建类对象的情况下可以直接调用静态方法

云外方天

#3 Created at ... [Delete] [Delete and Lock User]

在一个静态方法中调用另一个方法,被调用的方法必须也是静态的,否则只能通过创建被调用方法所属类的实例,使用“类实例名.被调用方法名”的方式调用。

Joker.fu_95

#4 Created at ... [Delete] [Delete and Lock User]

因为你在main函数里面调用同类的其他方法,想直接调用就必须是静态方法,因为main也是静态方法

世风冶行

#5 Created at ... [Delete] [Delete and Lock User]

如果想要删掉static,需要先定义类,具体代码如下:

public class Main{
    public static void main(String[] args) {
        // 给一个有普通收入、工资收入和享受国务院特殊津贴的小伙伴算税:
        Income[] incomes = new Income[] {
            new Income(3000),
            new Salary(7500),
            new StateCouncilSpecialAllowance(15000)
        };
        Main calculator = new Main(); // 创建test1的一个实例
        System.out.println(calculator.totalTax(incomes)); // 通过实例调用totalTax方法
    }

    public double totalTax(Income... incomes) { // totalTax现在是一个实例方法
        double total = 0;
        for (Income income : incomes) {
            total = total + income.getTax();
        }
        return total;
    }
}
//后续代码相同

  • 1

Reply