自己学校网站上的两道例题,主要就是考查了接口的上转型
1、
有个接口Camera,包含一个方法void takePicture()。现在有类CellPhone和IWatch如下,Travel类中的snap方法,需要一个参数Carema,现在请改造Cellphone和IWatch类,满足测试样例的输出要求
例如:
测试 | Result |
CellPhone cp=new CellPhone("Huawei"); IWatch iw=new IWatch("Apple"); Travel travel=new Travel(); travel.snap(cp); travel.snap(iw); | picture by Huawei cellphone picture by Apple iwatch |
import java.util.*;
interface Camera
{
void takePicture();
}
class CellPhone implements Camera
{
String name;
public CellPhone(String name)
{
this.name=name;
}
@Override
public void takePicture()
{
System.out.printf("picture by %s cellphone\n",this.name);
}
}
class IWatch implements Camera
{
String name;
public IWatch(String name)
{
this.name=name;
}
@Override
public void takePicture()
{
System.out.printf("picture by %s cellphone\n",this.name);
}
}
class Travel
{
public void snap(Camera c){
c.takePicture();
}
}
public class Main {
public static void main(String[] args) {
CellPhone cp=new CellPhone("Huawei");
IWatch iw=new IWatch("Apple");
Travel travel=new Travel();
travel.snap(cp);
travel.snap(iw);
}
}
2、
设计一个Car类,有一个车龄属性,构造函数初始化车龄
设计一个Company类,有个一个估值属性,构造函数初始化公司的估值
Car和Company都可以买保险,保险费车的是车龄乘以100,公司是估值除以100
设计一个Insurable接口,包括一个抽象方法getFee();
现在有个系统已经实现的People类中包含一个方法display(Insuable s),能够打印出输入参数的费用
根据下面测试样例的调用方式,你将如何设计?请完成类和接口的设计
测试
Result
Car p=new Car(20);
Company c=new Company(1000000);
People.display(p);
People.display(c);
2000.0
10000.0
import java.util.*;
class People{
public static void display(Insurable s){
System.out.println(s.getFee());
}
}
interface Insurable
{
Double getFee();
}
class Car implements Insurable
{
int s;
Car(int s)
{
this.s=s;
}
public Double getFee()
{
return this.s*100.0;
}
}
class Company implements Insurable
{
int s;
Company(int s)
{
this.s=s;
}
public Double getFee()
{
return this.s/100.0;
}
}
public class Main {
public static void main(String[] args) {
Car p=new Car(20);
Company c=new Company(1000000);
People.display(p);
People.display(c);
}
}
头歌
根据提示,在右侧编辑器补充代码:
声明一Person接口,并在里面声明三个常量:name、age、occupation,并分别赋值;
声明一Student类,此类实现Person接口,并复写Person中的talk()方法;
实例化一Student的对象s,并调用talk()方法,打印信息;
具体输出要求请看测试说明。
测试说明
测试输入:无预期输出:
学生——>姓名:张三,年龄:18,职业:学生!
package case7;
public class interfaceTest {
public static void main(String[] args) {
Student sb=new Student();
sb.talk();
}
}
interface Person
{
String name="张三";
String occupation="学生";
int age=18;
void talk();
}
class Student implements Person
{
public void talk()
{
System.out.printf("学生——>姓名:%s,年龄:%d,职业:%s!",this.name,this.age,this.occupation);
}
}