java接口 练习move
时间: 2023-09-10 12:14:33 浏览: 46
抽象接口 Moveable:
```java
public interface Moveable {
void move(int distance);
}
```
实现类 Car:
```java
public class Car implements Moveable {
private int distance = 0;
@Override
public void move(int distance) {
this.distance += distance;
System.out.println("Car moves " + distance + " meters.");
}
public int getDistance() {
return distance;
}
}
```
测试类 Main:
```java
public class Main {
public static void main(String[] args) {
Moveable m = new Car();
m.move(100);
m.move(200);
m.move(50);
Car car = (Car) m;
System.out.println("Total distance: " + car.getDistance() + " meters.");
}
}
```
输出:
```
Car moves 100 meters.
Car moves 200 meters.
Car moves 50 meters.
Total distance: 350 meters.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)