文件名称:java高级类操作 接口与抽象类的操作
文件大小:251KB
文件格式:DOC
更新时间:2013-05-31 08:31:32
抽象类 接口
本文是一个word讲义 介绍了 Figure circle Rectangle等类在接口中计抽象类中的用法 抽象类 接口多态 public class Polymorphism { public static void main(String args[]) { Triangle t=new Triangle(5.0,2.0); t.show_area(); Rectangle r=new Rectangle(3.0,4.0); r.show_area(); Circle c=new Circle(10.0); c.show_area(); } } abstract class Figure { protected double x=10.0,y=5.0; abstract void show_area(); } class Triangle extends Figure { Triangle(double a,double b) { x=a; y=b; } void show_area() { System.out.println("triangle:"+(0.5*x*y)); } } class Rectangle extends Figure { Rectangle(double a,double b) { x=a; y=b; } void show_area() { System.out.println("rectangle:"+(x*y)); } } class Circle extends Figure { Circle(double a){x=a;} final double pi=3.1416; void show_area() { System.out.println("circle:"+(pi*x*x)); } } package inf; interface Figure { abstract double area(); } //Rectangle.java package inf; /** * * @author tai */ public class Rectangle implements Figure{ double width,height; public Rectangle(double w,double h) //构造方法 { width=w; height=h; } public double area(){ return (width * height); } } //Triangle.Java package inf; /** * * @author tai */ class Triangle implements Figure { double a; double b; double c; Triangle(double a,double b,double c) { this.a=a; this.b=b; this.c=c; } public double area() { double p=(a+b+c)/2; return Math.sqrt(p*(p-a)*(p-b)*(p-c)); } } //Circle.java package inf; /** * * @author tai */ class Circle implements Figure { double radius; Circle(double radius) { this.radius=radius; } public double area() { return Math.PI*radius*radius; } } 测试一: public class Test4 { public static void main(String args[]) { Triangle t=new Triangle(5.0,6.0,7.0); System.out.println("三角形面积="+t.area()); Rectangle r=new Rectangle(3.0,4.0); System.out.println("矩形面积="+r.area()); Circle c=new Circle(10.0); System.out.println("圆的面积="+c.area()); } } 测试二: package inf; import javax.swing.JOptionPane; public class Test5 { public static double totalArea1(Figure f[]) { double totalArea=0; for(Figure f1:f){ totalArea+=f1.area(); } return totalArea; } public static void main(String args[]) { Figure f[] =new Figure[3];//为什么 f[0]=new Triangle(5.0,6.0,7.0); f[1]=new Rectangle(6.0,87.0); String input=JOptionPane.showInputDialog("输入圆的半径"); Double r=Double.parseDouble(input); f[2]=new Circle(r); double totalArea=0; for(Figure f1:f){ totalArea+=f1.area(); } JOptionPane.showMessageDialog(null,"totalarea="+totalArea); JOptionPane.showMessageDialog(null,"totalarea1="+totalArea1(f)); } }