如何传递一个方法从不同的类到另一个类在Java? [英] how to pass a method from different class to another class in Java?

查看:351
本文介绍了如何传递一个方法从不同的类到另一个类在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2个文件命名:


  1. AnnuityDueGUI.java

  2. AnnuityDueResultGUI.java

  1. AnnuityDueGUI.java
  2. AnnuityDueResultGUI.java

在AnnuityDueGUI.java中,有如下方法:

Under AnnuityDueGUI.java, there is this method as below:

== ===========

=============

public double calculateFADGUI(){
        //FVA = A{[(1+i)^n – 1] / i} (1+i)
        String amountStr = amount.getText() ;  //convert string to double
        dAmount = Double.parseDouble(amountStr) ;
        String iStr = iText.getText() ;
        dInterest = Double.parseDouble(iStr) ;
        String periodStr = period.getText() ;
        dPeriod = Double.parseDouble(periodStr) ;
        iPeriod = (int)dPeriod ;
        due = new Annuity(dAmount, dInterest, iPeriod) ;
        System.out.println(due.calculateFAD()) ;
        return due.calculateFAD() ;   //calculateFAD() is under Annuity.java
    }

====== =========

===============

在AnnuityDueResultGUI.java中,如何从上面提到的方法获取结果?两个类都在同一个包GUI。我也做了 import AnnuityDueGUI。*;

Under AnnuityDueResultGUI.java, how to grab the result from the method that I've stated above?both classes are under the same package "GUI". I also did import AnnuityDueGUI.* ;

但是还是不知道如何从AnnuityDueGUI获取结果。并在AnnuityDueResultGUI.java下显示它。

But still have no idea on how to grab the result from AnnuityDueGUI.java and display it under AnnuityDueResultGUI.java.

请提前协助并感谢。

推荐答案

您将需要对AnnuityDueResultGUI中的AnnuityDueGUI对象的引用。例如

You will need a reference to the AnnuityDueGUI object in AnnuityDueResultGUI. So for instance

AnnuityDueGUI adg = new AnnuityDueGUI()
double result = adg.calculateFADGUI()

UPDATE

如果你碰巧已经在其他地方构造AnnuityDueGUI,你只需要传递对AnnuityDueResultGUI的引用

Also if you happen to already be constructing the AnnuityDueGUI somewhere else you can just pass the reference to AnnuityDueResultGUI

public AnnuityDueResultGui(AnnuityDueGUI adg) {
    this.adg = adg;
}

private void otherFunc () {
    double results = this.adg.calculateFADGUI()
}

这篇关于如何传递一个方法从不同的类到另一个类在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆