无法获取getter的值

q8l4jmvw  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(275)

**结案。**此问题不可复制或由打字错误引起。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

上个月关门了。
改进这个问题
我是新来编码的。我有三节课 Payment , CashPayment ,和 MainClass . 我想访问getter的payment类的值 CashPayment 方法。我打电话来了 Payment 进入 MainClass 设置 amountOfPayment 示例,然后通过中的getter访问它 CashPayment . 但是,它总是返回0。
付款.java

public class Payment {
    public double amountOfPayment;

    public Payment(){}

    public double getAmountOfPayment() {
        return this.amountOfPayment;
    }

    public void setAmountOfPayment(double amountOfPayment) {
        this.amountOfPayment = amountOfPayment;
    }
}

现金支付.java

public class CashPayment {

    public String paymentDetails() {
        Payment payment = new Payment();
        return "Payment : " + payment.getAmountOfPayment();
    }

}

付款驱动程序.java

public class PaymentDriver {
    public static void main(String args[]){

        Payment payment = new Payment();
        payment.setAmountOfPayment(200);
        CashPayment cashPayment = new CashPayment();
        System.out.println(cashPayment.paymentDetails());
}
}

输出 Payment : 0.0 //这应该是200.0

6yoyoihd

6yoyoihd1#

你用的是完全不同的 Payment 对象中的对象示例 paymentDetails() 方法,而不是您尝试引用的方法。
有很多方法可以解决这个问题。一个简单的,但不一定是建筑优雅的方式将是定义您的 paymentDetails() 采取措施 Payment 参数并传入在中创建的参数 main() ```
public class CashPayment {

public String paymentDetails(Payment payment) {
return "Payment : " + payment.getAmountOfPayment();
}

vptzau2j

vptzau2j2#

还有其他方法可以实现:
继承
如果 CashPayment 扩展 Payment 类,然后是它的方法 paymentDetails 不需要创建另一个 Payment 对象:

public class CashPayment extends Payment {
    public String paymentDetails() {
        return "Payment : " + this.getAmountOfPayment();
    }
}

那么驱动程序/测试方法如下所示:

Payment payment = new CashPayment();
payment.setAmountOfPayment(200);
CashPayment cashPayment = (CashPayment) payment; // casting needed
System.out.println(cashPayment.paymentDetails());

输出:

Payment : 200.0

聚合(示例) CashPayment 有一个示例 Payment ):
Payment 需要将带有setter的字段添加到 CashPayment 班级。或者,可以通过构造函数设置此字段。

public class CashPayment {
    private Payment payment;

    public void setPayment(Payment payment) {
        this.payment = payment;
    }

    public String paymentDetails() {
        if (null != payment) {
            return "Payment : " + payment.getAmountOfPayment();
        }
        return "No payment set";
    }
}

驱动程序类更新:

Payment payment = new Payment();
payment.setAmountOfPayment(200);
CashPayment cashPayment = new CashPayment();

System.out.println("before setting: " + cashPayment.paymentDetails());
cashPayment.setPayment(payment);
System.out.println("after setting: " + cashPayment.paymentDetails());

输出:

before setting: No payment set
after setting: Payment : 200.0

相关问题