实验目的:掌握接口的定义及实现,掌握面向接口的编程思想
实验内容:
1、求任意柱体的体积(面向接口的编程思想)
2、动物园动物管理:动物们都会吃东西,但不同的动物吃的东西不一样;动物都会叫,但不同动物的叫声不一样;有的动物需要表演,有的动物不能表演;有的动物允许游客喂食物,有的不能喂食物;
实验步骤:
一. 求任意柱体的体积(面向接口的编程思想)
1.工程图:
2.实现步骤:
Circle类:
package com.xl.myshape;
import com.xl.shape.IShape;
public class Circle implements IShape {
double r;
public Circle() {
super();
}
public Circle(double r) {
super();
this.r = r;
}
@Override
public double getArea() {
// TODO 自动生成的方法存根
return Math.PI*r*r;
}
}
Cylinder类:
package com.xl.shape;
public class Cylinder {
public double height;
IShape shape;
public Cylinder() {
super();
}
public Cylinder(double height, IShape shape) {
super();
this.height = height;
this.shape = shape;
}
public double getVolume() {
return this.height*shape.getArea();
}
}
IShape接口:
package com.xl.shape;
public interface IShape {
//接口只存放:“常量”和“抽象方法”
double getArea();
}
Test主函数:
package com.xl.test;
import com.xl.myshape.Circle;
import com.xl.shape.Cylinder;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Circle c = new Circle(3);
Cylinder cy = new Cylinder(10,c);//接受回调
System.out.println(cy.getVolume());
}
}
运行结果:
二.动物园动物管理问题
1、工程图
2、实现步骤
Animal类:
package com.xl.animal;
public abstract class Animal {
public String name;
public abstract void eat();
public abstract void cry();
}
Dog类:
package com.xl.animal;
public class Dog extends Animal implements IFeed,IShow {
public Dog(String name) {
this.name = name;
}
@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println(this.name+"喜欢吃骨头");
}
@Override
public void cry() {
// TODO 自动生成的方法存根
System.out.println(this.name+"汪汪叫!");
}
@Override
public void show() {
// TODO 自动生成的方法存根
System.out.println(this.name+"不可以表演");
}
@Override
public void feed() {
// TODO 自动生成的方法存根
System.out.println(this.name+"不可以喂食物");
}
}
Monkey类:
package com.xl.animal;
public class Monkey extends Animal implements IFeed,IShow {
public Monkey(String name) {
this.name = name;
}
@Override
public void eat() {
// TODO 自动生成的方法存根
System.out.println(this.name+"喜欢吃水果");
}
@Override
public void cry() {
// TODO 自动生成的方法存根
System.out.println(this.name+"哇哇叫!");
}
@Override
public void show() {
// TODO 自动生成的方法存根
System.out.println(this.name+"会滑稽的表演");
}
@Override
public void feed() {
// TODO 自动生成的方法存根
System.out.println(this.name+"可以喂食物");
}
}
IShow:
package com.xl.animal;
public interface IShow {
public void show();
}
IFeed:
package com.xl.animal;
public interface IFeed {
public void feed();
}
Test主函数:
package test;
import com.xl.animal.Dog;
import com.xl.animal.Monkey;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Monkey mk = new Monkey("六耳猕猴");
mk.eat();
mk.cry();
mk.show();
mk.feed();
Dog dg = new Dog("哮天犬");
dg.eat();
dg.cry();
dg.show();
dg.feed();
}
}
运行结果: