JAVA初学记(一)利用多态性编程,实现求三角形、正方形和圆形的面积

xiaoxiao2025-10-06  26

package shape;

abstract public class shape {

abstract double getArea();

}

package shape;

public class circle extends shape{ double r=0; public circle(double r){ this.r=r; } double getArea(){ double s=0; return s=rrMath.PI; } }

package shape;

public class rectangle extends shape {

double x=0,y=0; rectangle(double x,double y){ this.x=x; this.y=y; } double getArea() { double s=0; return s=x*y; }

}

package shape;

public class triangle extends shape {

double a=0,b=0,c=0; triangle(double a,double b,double c) { this.a=a; this.b=b; this.c=c; } double getArea() { double s=0; double p=0; p=(a+b+c)/2; return s=Math.sqrt(p*(p-a)*(p-b)*(p-c)); }

}

package shape;

public class run {

public static void main(String[] args) { // TODO Auto-generated method stub shape sh[]=new shape[3]; sh[0]=new circle(1); sh[1]=new rectangle(2,4); sh[2]=new triangle(2,2,3); for(int i=0;i<3;i++) { System.out.println(sh[i].getArea()); } }

}

实验分析和总结 总的来说,很不习惯JAVA的按类分块编程,所以经常走弯路,比如说我会很奇怪为什么明明{}是匹配的,但就是报错,原来是必须由命名的class类做贯穿全部代码,而不是main。 还有关于父类shape,我总想把面积s和输出函数System.out.println()放进去,但总是失败,我明明用了super.s来访问shape中的s了,但不知道为什么,总是0。 还有,类好像必须分开定义,不然会报错,不过我不是很清楚会不会执行,毕竟我一直在报错,但结果是对的,或许是学的太少吧,路还很长。

转载请注明原文地址: https://www.6miu.com/read-5037475.html

最新回复(0)