Java 接口示例以及实现

来源:互联网 发布:座狼猎人 升星数据 编辑:程序博客网 时间:2024/06/10 18:07

接口的实现与类的继承是相似的,不同之处是:实现接口的类不从该接口的定义中继承任何行为,为实现该接口的类的任何对象中都能调用这个接口中定义的方法。接口实际上就是一个特殊的抽象类,同时实现多个接口就意味着有多重继承的功能。

package 接口示例;public interface Shape2D {double PI = 3.14;double grith();double area();}package 接口示例;import java.text.DecimalFormat;import java.util.Scanner;class Cricle implements Shape2D{double radius;public Cricle(double r){radius = r;}@Overridepublic double grith() {// TODO 自动生成的方法存根return 2*PI*radius;}@Overridepublic double area() {// TODO 自动生成的方法存根return PI*radius*radius;}}class Rectangle implements Shape2D{double width,heigth;public Rectangle(double w,double h){width = w; heigth = h;}@Overridepublic double grith() {// TODO 自动生成的方法存根return 2*(width+heigth);}@Overridepublic double area() {// TODO 自动生成的方法存根return width*heigth;}}public class InterfaceExample {public static void main(String[] args) {// TODO 自动生成的方法存根DecimalFormat df = new DecimalFormat("0.00");Scanner scan = new Scanner(System.in);System.out.print("请输入圆的半径 r = ");double r;r = scan.nextInt();Cricle cricle = new Cricle(r);System.out.println("此圆的周长为:"+ df.format(cricle.grith()));System.out.println("此圆的面积为:"+ df.format(cricle.area()));System.out.println();System.out.print("请输入矩形的长 h = ");double h;h = scan.nextInt();System.out.print("请输入矩形的长 w = ");double w;w = scan.nextInt();Rectangle rectangle = new Rectangle(w, h);System.out.println("此矩形的周长为:"+ df.format(rectangle.grith()));System.out.println("此矩形的面积为:"+ df.format(rectangle.area()));}}

0 0
原创粉丝点击