
一道简单的JAVA程序设计题。。用了abstract....下面是偶做的。不知道错在哪里。求指点。。。
abstractclassShapes{abstractprotecteddoublearea();abstractprotecteddoublegirth();}cla...
abstract class Shapes{
abstract protected double area();
abstract protected double girth();
}
class Rectangle extends Shapes{
float width,length;
Rectangle(float w,float l){
width=w;
length=l;
}
public double area(){
return width*length;
}
public double girth(){
return (width+length)*2;
}
}
class Circle extends Shapes{
float radius;
Circle(float r){
radius=r;
}
public double area1(){
return radius*radius;
}
public double girth1(){
return 2*3.14*radius;
}
}
class Shape_ex{
public static void main(String args[]){
Rectangle rc=new Rectangle(6,12);
System.out.println("The area of rectangle:"+rc.area());
System.out.println("The girth of rectangle:"+rc.girth());
System.out.println();
Circle Ci=new Circle(3);
System.out.println("The area of Circle:"+Ci.area1());
System.out.println("The girth of Circle:"+Ci.girth1());
}
} 展开
abstract protected double area();
abstract protected double girth();
}
class Rectangle extends Shapes{
float width,length;
Rectangle(float w,float l){
width=w;
length=l;
}
public double area(){
return width*length;
}
public double girth(){
return (width+length)*2;
}
}
class Circle extends Shapes{
float radius;
Circle(float r){
radius=r;
}
public double area1(){
return radius*radius;
}
public double girth1(){
return 2*3.14*radius;
}
}
class Shape_ex{
public static void main(String args[]){
Rectangle rc=new Rectangle(6,12);
System.out.println("The area of rectangle:"+rc.area());
System.out.println("The girth of rectangle:"+rc.girth());
System.out.println();
Circle Ci=new Circle(3);
System.out.println("The area of Circle:"+Ci.area1());
System.out.println("The girth of Circle:"+Ci.girth1());
}
} 展开
2个回答
展开全部
编译时是这样的结果: Circle不是抽象的, 并且未覆盖Shapes中的抽象方法girth()。
在《java编程思想》第9.1章(第169页)上的原话:“如果从一个抽象类继承,并想创建该新类的对象,那么就必须为基类中的所有方法提供方法定义。”就是说,Circle类是继承于抽象类Shapes的,那么Shape中的两个抽象函数就必须在Circle类中得到实现。细心的你应该可以看出,同样是继承于Shape类的Rectangle类,编译时该类的定义没有出错。
改错 很简单 ,你只需要将函数定义处和结尾引用处的area1改为area,girth1改为girth即可,由于Circle类和Rectangle类是独立的,因此即使两个类中的函数名相同,也不影响的。
在《java编程思想》第9.1章(第169页)上的原话:“如果从一个抽象类继承,并想创建该新类的对象,那么就必须为基类中的所有方法提供方法定义。”就是说,Circle类是继承于抽象类Shapes的,那么Shape中的两个抽象函数就必须在Circle类中得到实现。细心的你应该可以看出,同样是继承于Shape类的Rectangle类,编译时该类的定义没有出错。
改错 很简单 ,你只需要将函数定义处和结尾引用处的area1改为area,girth1改为girth即可,由于Circle类和Rectangle类是独立的,因此即使两个类中的函数名相同,也不影响的。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询