我有两个类:“Add.java”和“Subtract.java”。我想在“subfn”方法(类 Subtract )中使用“addfn”方法(类添加)的结果。我该怎么办?
Add.java
public class Add
{
public double a, b;
public double addfn(double a, double b)
{
return (a+b);
}
}
Subtract.java
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 扩展课程添加,如下所示:
public class Subtract extends Add
但是Java只是为 a 和 b 分配了空值,因此 c 总是变为0.它也无法让我访问来自添加类的“addfn”。
我该怎么办?感谢。
编辑:感谢您的所有答案,但我如何专门从另一个类中运行一个函数?我怎样才能立即运行这两个功能?再次感谢。答案 0 :(得分:0)
Add obj1 = new Add();
c = obj1.addfn(obj1.a,obj1.b);
return (c-d);
答案 1 :(得分:0)
在Add
班级中,行public double a, b;
不执行任何操作,因为addfn
方法仅添加并返回方法参数。
自Subtract
扩展Add
以来,您可以直接使用addfn。
public double subfn(double d)
{
c = addfn(5+10);
return (c-d);
}