嗯。。快期末考试了,预习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;
}
}
}