java接口练习1
/**2.编程题:
利用接口做参数,写个计算器,能完成加减乘除运算。
(1)定义一个接口Compute含有一个方法int computer(int n, int m)。
(2)设计四个类分别实现此接口,完成加减乘除运算。
(3)设计一个类UseCompute,类中含有方法:public void useCom(Compute com, int one, int two),
此方法能够用传递过来的对象调用computer方法完成运算,并输出运算的结果。
(4)设计一个主类Test,调用UseCompute中的方法useCom来完成加减乘除运算。
*/
interface IComputer{
int computer(int n, int m);
}
class Add implements IComputer{
public int computer(int n, int m){
return n+m;
}
}
class Sub implements IComputer{
public int computer(int n, int m){
return n-m;
}
}
class Mul implements IComputer{
public int computer(int n, int m){
return n*m;
}
}
class Div implements IComputer{
public int computer(int n, int m){
try{
return n/m;
}catch(Exception e){
System.out.println(e.getMessage());
}
return -1;
}
}
class UseCompute{
public static void useCom(IComputer com, int one, int two){
int result = com.computer(one,two);
System.out.println(result);
}
}
public class Test5{
public static void main(String[] agrs){
UseCompute.useCom(new Add(),12,6);
UseCompute.useCom(new Sub(),12,6);
UseCompute.useCom(new Mul(),12,6);
UseCompute.useCom(new Div(),12,6);
UseCompute.useCom(new Div(),12,0);
}
}
/**3.按如下要求编写Java程序:
(1)定义接口A,里面包含值为3.14的常量PI和抽象方法double area()。
(2)定义接口B,里面包含抽象方法void setColor(String c)。
(3)定义接口C,该接口继承了接口A和B,里面包含抽象方法void volume()。
(4)定义圆柱体类Cylinder实现接口C,该类中包含三个成员变量:底圆半径radius、
圆柱体的高height、颜色color。
(5)创建主类来测试类Cylinder。
*/
interface A{
double PI = 3.14;
double area();
}
interface B{
void setColor(String c);
}
interface C extends A,B {
void volume();
}
class Cylinder implements C {
private double radius;
private double height;
private String color;
public Cylinder(double radius, double height, String color){
this.radius = radius;
this.height = height;
this.color = color;
}
public void setColor(String c){
this.color = c;
}
public String getColor(){
return this.color;
}
public double area(){
return PI*radius*radius;
}
public void volume(){
System.out.println("圆柱体的体积为:"+this.area()*this.height);
}
}
public class Test6{
public static void main(String[] agrs){
System.out.println("test c1:");
A c1 = new Cylinder(1,1,"red");
System.out.println("面积:"+c1.area());
System.out.println(((Cylinder)c1).getColor());
System.out.println("test c2:");
B c2 = new Cylinder(2,2,"blue");
System.out.println("面积:"+((Cylinder)c2).area());
System.out.println(((Cylinder)c2).getColor());
c2.setColor("green");
System.out.println(((Cylinder)c2).getColor());
System.out.println("test c3:");
C c3 = new Cylinder(1,2,"blank");
System.out.println("面积:"+c3.area());
c3.volume();
System.out.println(((Cylinder)c3).getColor());
}
}