标签:str end ati 图形 mat turn private style a+b
(一)抽象类的使用
2.编程技巧
(1) 抽象类定义的方法在具体类要实现;
(2) 使用抽象类的引用变量可引用子类的对象;
(3) 通过父类引用子类对象,通过该引用访问对象方法时实际用的是子类的方法。可将所有对象存入到父类定义的数组中。
1.代码源
public abstract class Shape { public abstract double getArea(Shape sh); } public class Circle extends Shape{ private double r = 0; public Circle(double r) { this.r = r; } public double getArea(Shape sh) { // TODO Auto-generated method stub double s = 0; s = this.r * this.r * Math.PI; return s; } } public class Rectangle extends Shape{ private double a = 0; private double b = 0; public Rectangle(double a, double b) { this.a = a; this.b = b; } public double getArea(Shape sh) { // TODO Auto-generated method stub double s = 0;//面积 s = this.a * this.b; return s; } } public class Triangle extends Shape{ private double a = 0; private double b = 0; private double c = 0; public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } public double getArea(Shape sh) { // TODO Auto-generated method stub double s = 0;//面积 double p = (a + b + c)/2; s = Math.sqrt(p*(p-a)*(p-b)*(p-c)); return s; } } public class Test { public static void main(String agrs[]) { Shape sh[] = new Shape[3]; sh[0] = new Circle(2); sh[1] = new Rectangle(2, 3); sh[2] = new Triangle(2, 2, 3); for (int i = 0; i < 3; ++i) { System.out.println(sh[i].getArea(sh[i])); } } }
(二)使用接口技术
1定义接口Shape,其中包括一个方法size(),设计“直线”、“圆”、类实现Shape接口。分别创建一个“直线”、“圆”对象,将各类图形的大小输出。
(1) 接口中定义的方法在实现接口的具体类中要重写实现;
(2) 利用接口类型的变量可引用实现该接口的类创建的对象。
标签:str end ati 图形 mat turn private style a+b
原文地址:https://www.cnblogs.com/Allen15773771785/p/11650802.html