创建3个接口,3个接口对应的3个类,3个类下面对应的方法要包含循环、条件语句和数组结构以及对应的操作,调用这些类和接口创建对象,执行出正常的结果
时间: 2024-03-26 17:35:05 浏览: 52
好的,我可以为您创建三个接口和对应的三个类,让它们包含循环、条件语句和数组结构以及对应的操作:
1. `Shape`接口包含了`getArea()`和`getPerimeter()`方法,使用了循环结构和条件语句。
```
public interface Shape {
double getArea();
double getPerimeter();
}
```
2. `Rectangle`类实现`Shape`接口,包含了`getArea()`和`getPerimeter()`方法,并且使用了数组结构和条件语句。
```
public class Rectangle implements Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
@Override
public double getPerimeter() {
return 2 * (width + height);
}
public boolean isSquare() {
return width == height;
}
}
```
3. `Vehicle`接口包含了`start()`和`stop()`方法,使用了条件语句。
```
public interface Vehicle {
void start();
void stop();
}
```
4. `Car`类实现`Vehicle`接口,包含了`start()`和`stop()`方法,并且使用了循环结构和条件语句。
```
public class Car implements Vehicle {
private String brand;
private boolean isRunning;
public Car(String brand) {
this.brand = brand;
this.isRunning = false;
}
@Override
public void start() {
if (isRunning) {
System.out.println(brand + " is already running");
} else {
System.out.println(brand + " starts");
isRunning = true;
}
}
@Override
public void stop() {
if (isRunning) {
System.out.println(brand + " stops");
isRunning = false;
} else {
System.out.println(brand + " is already stopped");
}
}
public void drive(int distance) {
for (int i = 0; i < distance; i++) {
System.out.println(brand + " has driven " + i + " miles");
}
}
}
```
接下来,我们可以创建对象并调用它们的方法:
```
Shape shape = new Rectangle(5, 5);
System.out.println("Area: " + shape.getArea());
System.out.println("Perimeter: " + shape.getPerimeter());
if (((Rectangle) shape).isSquare()) {
System.out.println("It's a square!");
} else {
System.out.println("It's not a square.");
}
Vehicle vehicle = new Car("Toyota");
vehicle.start();
vehicle.drive(10);
vehicle.stop();
vehicle.start();
vehicle.stop();
```
输出结果为:
```
Area: 25.0
Perimeter: 20.0
It's a square!
Toyota starts
Toyota has driven 0 miles
Toyota has driven 1 miles
Toyota has driven 2 miles
Toyota has driven 3 miles
Toyota has driven 4 miles
Toyota has driven 5 miles
Toyota has driven 6 miles
Toyota has driven 7 miles
Toyota has driven 8 miles
Toyota has driven 9 miles
Toyota stops
Toyota starts
Toyota stops
```
阅读全文