Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从另一个类执行(调用)一个类的函数?_Java_Bluej - Fatal编程技术网

Java 如何从另一个类执行(调用)一个类的函数?

Java 如何从另一个类执行(调用)一个类的函数?,java,bluej,Java,Bluej,我有两个类:“Add.java”和“Subtract.java”。我想在“subfn”方法(类减法中使用“addfn”方法(类的Add)的结果。我该怎么做 Add.java public class Add { public double a, b; public double addfn(double a, double b) { return (a+b); } } public class Subtract { double c, d;

我有两个类:“Add.java”和“Subtract.java”。我想在“subfn”方法(类减法中使用“addfn”方法(类的Add)的结果。我该怎么做

Add.java

public class Add
{
    public double a, b;
    public double addfn(double a, double b)
    {
     return (a+b);
    }
}
public class Subtract
{
    double c, d;
    public double subfn(double d)
    {
        //
        //I want the "addfn" from class "Add" to accept the variables *a* and *b*
        //and then use "subfn" to use the result of "addfn" and assign it to *c*
        //
        Add obj1 = new Add();
        //Can I somehow access the "addfn" method here?
        c = a+b;               //and then assign its result to c here?
        return (c-d);
    }
}
Subtract.java

public class Add
{
    public double a, b;
    public double addfn(double a, double b)
    {
     return (a+b);
    }
}
public class Subtract
{
    double c, d;
    public double subfn(double d)
    {
        //
        //I want the "addfn" from class "Add" to accept the variables *a* and *b*
        //and then use "subfn" to use the result of "addfn" and assign it to *c*
        //
        Add obj1 = new Add();
        //Can I somehow access the "addfn" method here?
        c = a+b;               //and then assign its result to c here?
        return (c-d);
    }
}
我尝试用类减法扩展类Add,如下所示:

public class Subtract extends Add
但Java只是将空值分配给a和b,因此c总是变成0。它也不能让我从Add类访问“addfn”

我该怎么做?谢谢


编辑:谢谢你的回答,但是我怎样才能从另一个类运行一个函数呢?我如何能够立即连续运行这两个函数?再次感谢。

在您的
添加
类中,行
公共双a、b
什么也不做,因为
addfn
方法只添加并返回方法参数

    Add obj1 = new Add();
    c = obj1.addfn(obj1.a,obj1.b);
    return (c-d);
由于
Subtract
扩展了
Add
,因此可以直接使用addfn

public double subfn(double d)
{
    c = addfn(5+10);
    return (c-d);
}

a和b变量存在于类add中,现在开始。他只是问如何访问函数,不是变量,而是。。。