在java中的另一个类中返回类构造函数字符串

时间:2016-09-17 00:42:59

标签: java

我有一个类贷款,它有一个设置字符串totalpaymentamt的构造函数

我还有另一个类贷款测试,它有main方法,并使用它来输出字符串

我已经完成了

public class Loan {
    public Loan() {
        String totalpaymentamt = "\t toString() results" + this.toString(this.getDuration(),
            this.getInterestRate(),
            this.gettotalAmount()) + "  \n \t getNumberOfYears() results:" + this.getDuration() + " getInterestRate() results:" + this.getInterestRate() + "  getTotalAmount() results:" + this.gettotalAmount() + " getMonthlyPayment:" + this.getMonthlyPayment(this.getDuration(),
            this.getInterestRate(),
            this.gettotalAmount());
    }
}

另一个班级是

public Loan(int duration, double interestRate, double totalAmount) {
     this.totalpaymentamt = "\t toString() results" + this.toString(duration, interestRate, totalAmount)

     + "  \n \t getNumberOfYears() results:" + duration
         + " getInterestRate() results:" + interestRate + "  getTotalAmount() results:" + totalAmount + " getMonthlyPayment:" + this.getMonthlyPayment(duration, interestRate, totalAmount);

}

这不会返回任何东西。我理解构造函数没有return语句,如何将贷款构造函数的结果返回给Testloan类main方法

1 个答案:

答案 0 :(得分:4)

构造函数不返回任何内容。

此外,在TestLoan类中,您正在扩展Loan类,而您不需要这样做。

如果您将贷款类构造函数更改为以下内容:

public class Loan {
    private String totalpaymentamt;

    public Loan() {

        this.totalpaymentamt = "\t toString() results"
                + this.toString(this.getDuration(),
                        this.getInterestRate(),
                        this.gettotalAmount())
                + "  \n \t getNumberOfYears() results:"
                + this.getDuration()
                + " getInterestRate() results:"
                + this.getInterestRate()
                + "  getTotalAmount() results:"
                + this.gettotalAmount()
                + " getMonthlyPayment:"
                + this.getMonthlyPayment(this.getDuration(),
                        this.getInterestRate(),
                        this.gettotalAmount());

    }


    public String getTotalPaymentAmount() {
        return this.totalpaymentamt;
    }
}

然后,在TestLoan中,你可以这样做:

Loan loan = new Loan();
System.out.println("First Loan \n " + loan.getTotalPaymentAmount());