1. 首页
  2. 编程语言
  3. Java
  4. java高级类操作 接口与抽象类的操作

java高级类操作 接口与抽象类的操作

上传者: 2021-04-18 19:27:38上传 APPLICATION/MSWORD文件 251KB 热度 18次
本文是一个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.
用户评论