定义父类Phone函数:
public abstract class Phone {
private String brand;
private int price;
public Phone() {}
public Phone(String brand,int price) {
this.brand=brand;
this.price=price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public abstract void sendMessage();
public abstract void call();
}
定义接口:
public interface Iplay {
public void playGame();
}
定义旧手机类继承手机类:
public final class OldPhone extends Phone {
public OldPhone() {}
public OldPhone(String brand,int price) {
super(brand,price);
}
public void sendMessage() {
System.out.println("用旧手机发短信");
}
public void call() {
System.out.println("用旧手机打电话");
}
}
定义新手机类继承手机类并连接接口:
public final class NewPhone extends Phone implements Iplay{
public NewPhone() {}
public NewPhone(String brand,int price) {
super(brand,price);
}
@Override
public void sendMessage() {
System.out.println("用新手机发短信");
}
@Override
public void call() {
System.out.println("用新手机打电话");
}
@Override
public void playGame() {
System.out.println("新手机可以玩王者荣耀");
}
}
定义测试类:
public class Test {
public static void main(String[] args) {
OldPhone op=new OldPhone();
op.setBrand(“摩托罗拉”);
op.setPrice(200);
System.out.println(op.getBrand()+"\t"+op.getPrice());
op.sendMessage();
op.call();
System.out.println("-----------------------");
NewPhone np=new NewPhone();
np.setBrand(“iphone”);
np.setPrice(8000);
System.out.println(np.getBrand()+"\t"+np.getPrice());
np.sendMessage();
np.call();
np.playGame();
}
}
运行结果:
摩托罗拉 200
用旧手机发短信
用旧手机打电话
iphone 8000
用新手机发短信
用新手机打电话
新手机可以玩王者荣耀