JAVA继承问题,实际参数列表与形式参数列表长度不同怎么解决

import java.lang.Math;

class Cylinder{
public double radius,height;
public Cylinder(double radius,double height){
this.radius=radius;
this.height=height;
}
double superficialarea(){
return 2*Math.PI*radius*radius+2*Math.PI*radius*height;
}
double volume(){
return Math.PI*radius*radius*height;
}
void show(){
System.out.println("圆柱体的表面积:"+superficialarea()+"圆柱体的体积:"+volume());
}
}

class Ringcylinder extends Cylinder{
double innerradius;
public Ringcylinder(double radius,double height,double innerradius){
this.radius=radius;
this.height=height;
this.innerradius=innerradius;
}
void setinnerradius(double innerradius){
this.innerradius=innerradius;
}
double superficialarea(){
return 2*(Math.PI*radius*radius-Math.PI*innerradius*innerradius)+2*Math.PI*(radius+innerradius)*height;
}
double volume(){
return Math.PI*(radius*radius-innerradius*innerradius)*height;
}
void show(){
System.out.println("环柱体的表面积:"+superficialarea()+"环柱体的体积:"+volume());
}
}

public class Test{
public static void main(String[] args){
Cylinder a=new Cylinder(5,10);
a.show();
Ringcylinder b=new Ringcylinder(5,10,1);
b.show();
}
}

public Ringcylinder(double radius,double height,double innerradius){
this.radius=radius;
this.height=height;
this.innerradius=innerradius;
}

这个构造函数虽然定义了radius, height, innerradius,但在print之前没有给构造函数传入这个几个参数,所以导致出现此问题,再调用print之前,可以设置Ringcylinder(0.5,3,1),这样构造函数才能进行初始化全局变量,全局变量才能计算。不然首先没有参数为空的构造函数,有没有将参数传入,必然会报错。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-23
Cylinder缺少一个空参构造函数
public Cylinder() {
super();
}

因为在Ringcylinder的构造函数中会默认调用
super();
而Cylinder不存在该构造函数所以报错。本回答被提问者和网友采纳
第2个回答  2013-09-16
首先,构造函数时可以重载的,可以解决你的标题中的问题

而,你的代码中的问题并不像你的标题那样,这是因为继承中,基类没有办法构造造成的(基类没有默认构造函数,或者没有给基类提供参数)。
第3个回答  2013-09-16
在Cylinder类中写个什么参数都不带的构造方法就完美了
相似回答