近日,学习Java时,看到如下程序,有一个问题想不明白,希望大家帮忙看看
abstract class Geometry{
public abstract double ComputerArea();
}
class Lader extends Geometry{
double a,b,h;
Lader(double a,double b,double h){
this.a = a;
this.b = b;
this.h = h;
}
public double ComputerArea(){
return((1/2.0)*(a+b)*h);
}
}
class Cone{
Geometry bottom;
double height;
Cone(Geometry bottom,double height){
this.bottom = bottom;
this.height = height;
}
void changeBottom(Geometry bottom){
this.bottom = bottom;
}
public double ComputerVolume(){
return(bottom.ComputerArea()*height)/3.0;
}
}
public class GraphicsTest{
public static void main(String[] args){
Cone cone;
Geometry geometry;
geometry = new Lader(2.0,7.0,10.7);//对象的上转型
System.out.println("梯形的面积" + geometry.ComputerArea());//输出面积,都没有问题
cone = new Cone(geometry,30);//问题
System.out.println("梯形底的椎的体积" + cone.ComputerVolume());
}
}
问题?
在这里的第一个参数为geometry类型的,它的值是什么,从哪里来的??
根据输出的结果可以判定geormetry的值是geormetry.ComputerArea()的值,为什么?
abstract class Geometry{
public abstract double ComputerArea();
}
class Lader extends Geometry{
double a,b,h;
Lader(double a,double b,double h){
this.a = a;
this.b = b;
this.h = h;
}
public double ComputerArea(){
return((1/2.0)*(a+b)*h);
}
}
class Cone{
Geometry bottom;
double height;
Cone(Geometry bottom,double height){
this.bottom = bottom;
this.height = height;
}
void changeBottom(Geometry bottom){
this.bottom = bottom;
}
public double ComputerVolume(){
return(bottom.ComputerArea()*height)/3.0;
}
}
public class GraphicsTest{
public static void main(String[] args){
Cone cone;
Geometry geometry;
geometry = new Lader(2.0,7.0,10.7);//对象的上转型
System.out.println("梯形的面积" + geometry.ComputerArea());//输出面积,都没有问题
cone = new Cone(geometry,30);//问题
System.out.println("梯形底的椎的体积" + cone.ComputerVolume());
}
}
问题?
在这里的第一个参数为geometry类型的,它的值是什么,从哪里来的??
根据输出的结果可以判定geormetry的值是geormetry.ComputerArea()的值,为什么?
如果有值得话,值是怎么分配的?为什么就是geometry.ComputerArea()的值?谢谢!
----------------------------------------------
是啊,public double ComputerVolume(){
return(bottom.ComputerArea()*height)/3.0;
}
这里不是调用了实例的方法了么?
cone = new Cone(geometry,30);//问题
这是以一个Geometry和一个double型构造了一Cone对象,Cone对象里有成员变量Geometry,可以调用其方法
geormetry是一个对象实例的引用,它当然有值,但是它的值只是为了指示实例的位置。
在Cone中也是用了
return(bottom.ComputerArea()*height)/3.0;什么地方直接用geormetry本身的值了?
那个值是从哪里来的??
所以 cone = new Cone(geometry,30);//问题
这里的参数 geometry 就是一个实实在在的对象了!
还是那个问题,你从什么地方看出来“geormetry的值是geormetry.ComputerArea()的值”了?
geormetry.xxx可以提取此空间的值,或则调用储存的函数
对吗??刚开始学,确实有许多地方不明白,
而且这些在书中也没有讲到。这是一个书上的,例题。谢谢大家了!
就是(geometry,30)中的geormetry是怎么找到需要的值的??楼上flyforlove说过是通过cone = new Cone(geometry,30);把值传过去的
可是在Cone(Geometry bottom,double height){
this.bottom = bottom;
this.height = height;
}
中,我怎么没有看出来! bottom也是Geormetry类型, geormetry也是Geormetry类型,
两个引用具有相同的地址,可这两个引用我没有发现引用的值是什么??谢谢!!!
System.out.println(o);这个年度最佳教练我就不再当了。:(
这就是你问题的答案!
说说我的想法:
我一直认为函数的返回值是在对象的引用在调用方法时,利用其返回值得到一个数而已
没有想过能将返回值传给对象,这个是什么原理?
这几天我也一直在查阅相关资料,但是都没有找到理想的答案
所以能讲一下将返回值传给对象的原理么??再次谢谢大家!