接口练习: 设计接口Action表示人的活动,抽象方法有say(String msg);eating(String food); 设计抽象类Person,成员变量name和age,重写toString()方法,省略构造方法和setter、getter方法; 定义Worker类实现Action接口继承Person类。 定义Teacher类实现Action接口继承Person类。
时间: 2023-11-27 22:53:11 浏览: 178
java:接口和抽象类练习
5星 · 资源好评率100%
接口Action的代码如下:
```java
public interface Action {
void say(String msg);
void eating(String food);
}
```
抽象类Person的代码如下:
```java
public abstract class Person {
protected String name;
protected int age;
@Override
public String toString() {
return "Name: " + name + ", Age: " + age;
}
}
```
Worker类的代码如下:
```java
public class Worker extends Person implements Action {
public Worker(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void say(String msg) {
System.out.println(name + " says: " + msg);
}
@Override
public void eating(String food) {
System.out.println(name + " is eating " + food);
}
}
```
Teacher类的代码如下:
```java
public class Teacher extends Person implements Action {
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public void say(String msg) {
System.out.println(name + " says: " + msg);
}
@Override
public void eating(String food) {
System.out.println(name + " is eating " + food);
}
}
```
以上代码实现了Action接口和Person抽象类,并定义了Worker和Teacher类分别实现Action接口并继承Person类。Worker和Teacher类实现了Action接口中的抽象方法say和eating,以及继承自Person类的toString方法。
阅读全文