假设我有A级和B级。那么,在main中,是否可以获得A类的返回值?我现在正在做作业,但似乎无法让它们正确,所以这里我想问的例子......
public class A
{
private double total=10;
public double test()
{
return total;
}
}
public class B extends A
{
private double totalB=20;
public double test()
{
return (super.test()+10);
}
}
public class C
{
public static void main(String [] args)
{
double Sum;
B FTest = new B();
System.out.println("I want to get back return value of class A for calculate\n"+FTest.test()/2);
//So the answer i want to get is suppose to be 5
System.out.println("Again i want to use return value of class A\n"+FTest.test()*10);
//Here the value i want to get is 10*10 = 100
}
}
我得到的答案
I want to get back return value of class A for calculate
30.0
Again i want to use return value of class A
300.0
我想要的答案
I want to get back return value of class A for calculate
5
Again i want to use return value of class A
100
所以我问的直接问题是我能在主要的A类中调用test()方法 B对象。如果可以,怎么样?
答案 0 :(得分:1)
由于您已创建了类B
的对象,因此您可以获取已在类A
中初始化的变量的值,除非您修改了B类test()
方法
答案 1 :(得分:1)
super
关键字可让您访问超类的属性和方法。
由于total
中的A
是私有的,因此您需要通过A
的{{1}}方法获取它。
因此,test
应该成为:
B
答案 2 :(得分:0)
这里是我可以写的代码..更多关于你提交的代码中有很多关于类和变量定义的混合器..等等,请参考你的资料
class A
{
int total=10;
public double test()
{
return total;
}
}
class B extends A
{
private int total=20;
public double test()
{
return total+10;
}
}
public class C
{
public static void main(String [] args)
{
A class1 = new A();
System.out.println("I want to get back return value of class A for calculate");
//So the answer i want to get is suppose to be 5
//If override occur only the second time i invoke the method, then how about i want to use it back again? For calculation.....
System.out.println("Again i want to use return value of class A"+class1.test()*10);
//Here the value i want to get is 10*10 = 100
}
}