Java 接口实现

嗯。。快期末考试了,预习Java开始。/(ㄒoㄒ)/~~

一个类可以遵循多个接口,但必须实现接口的所有方法,不然会报错。


定义一个接口 :

[public] interface InterfaceName {
	function1();
	function2();
	.
	.
	.
}

而某一个类要遵循一个接口需要使用implements关键字

class ClassName implements Interface1,Interface2,[....]{
    
}



接口的调用(多态实现)

InterfaceName AnObject = new ClassName();

具体的用法还是看代码吧。。

这个是我从学校OJ上找的,题号SDUT3338

import java.util.*;
public class Main{
	public static void main(String [] args){
		Scanner sc = new Scanner (System.in);
		while(true){
			String s = sc.nextLine();
			String a [] = s.split(" ");
			Shape sh = null;
			if(a.length == 1){
				sh = new Circle(Double.parseDouble(a[0]));//接口和多态
			}
			else if(a.length == 2){
				sh = new Rectangle(Double.parseDouble(a[0]),Double.parseDouble(a[1]));
			}
			else if(a.length == 3){
				sh = new Triangle(Double.parseDouble(a[0]),Double.parseDouble(a[1]),Double.parseDouble(a[2]));
			}
			System.out.printf("%.2f\n",sh.length());
		}
	}
}

interface Shape{
	double length(); //定义一个接口
}

class Circle implements Shape{ //接口的实现
	static final double PI=3.14;
	private double r;
	public double length(){
		return Circle.PI*2.0*r;
	}
	public Circle(double r){
		if(r>=0)this.r=r;
		else this.r=0;
	}
}

class Rectangle implements Shape{
	private double l,h;
	public double length(){
		return 2.0*(this.l+this.h);
	}
	public Rectangle(double l,double h){
		if(l<=0||h<=0){
			this.l=0;
			this.h=0;
		}
		else{
			this.l=l;
			this.h=h;
		}
	}
}

class Triangle implements Shape{
	private double a,b,c;
	public double length(){
		return a+b+c;
	}
	public boolean Judge(double ...c){
		Arrays.sort(c);
		if(c[0]+c[1]>c[2]) return true;
		else return false;
	}
	public Triangle(double a,double b,double c){
		if(a<=0||b<=0||c<=0||!Judge(a,b,c)){
			this.a=0;
			this.b=0;
			this.c=0;
		}
		else{
			this.a=a;
			this.b=b;
			this.c=c;
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值