2读程序,改正程序中的错误
public class Class1
{
public static void main (String[] args)
{ B b=new A( ); //创建B的对象
b.myPrint(1.2f);
}
}
class A
{
float rear(float r)
{
return (float)Math.PIrr;
}
class B extends A
{
float rear(float r)
{
return 4*(float)Math.PIrr;
}
MyPrint(float r)
{
System.out.println("半径为 "+r"的圆的面积="+super.rear(r) +"同半径的球的表面积="+rear(r));
}
问题如下:
向下转型,需要强转。
B b=new A( ); 改为 B b=(B) new A( );
B类重写的方法上需要加@Override
@Override
float rear(float r) {
return 4 * (float) Math.PI*r*r;
}
加上返回类型void
void MyPrint(float r) {
System.out.println("半径为 " + r+"的圆的面积=" + super.rear(r) + "同半径的球的表面积=" + rear(r));
}
B b=new A( ); 这句就是错的,基类对象赋值给子类就不行。