创建3个类下面对应的方法要包含循环,条件语句,数组结构以及对应的操作
时间: 2024-03-26 10:35:00 浏览: 58
好的,我可以为您创建三个类来演示这些内容:
1. `Animal`类实现`Animal`接口,包含了`eat()`和`sleep()`方法,并且使用循环结构和条件语句。
```
public class Animal implements Animal {
private String name;
private int age;
private String[] foods;
public Animal(String name, int age, String[] foods) {
this.name = name;
this.age = age;
this.foods = foods;
}
@Override
public void eat() {
for (String food : foods) {
if (food.equals("grass")) {
System.out.println(name + " likes to eat " + food);
} else {
System.out.println(name + " does not like to eat " + food);
}
}
}
@Override
public void sleep() {
int hours = age <= 2 ? 10 : 8;
System.out.println(name + " sleeps for " + hours + " hours a day");
}
}
```
2. `Bird`类继承`Animal`类,并且实现了`Flying`接口,包含了`fly()`方法和数组结构。
```
public class Bird extends Animal implements Flying {
private String[] colors;
public Bird(String name, int age, String[] foods, String[] colors) {
super(name, age, foods);
this.colors = colors;
}
@Override
public void fly() {
System.out.println(name + " can fly");
for (String color : colors) {
System.out.println(name + " has " + color + " feathers");
}
}
}
```
3. `Fish`类实现`Swimming`接口,包含了`swim()`方法和条件语句。
```
public class Fish implements Swimming {
private String name;
private int age;
private boolean isFreshwater;
public Fish(String name, int age, boolean isFreshwater) {
this.name = name;
this.age = age;
this.isFreshwater = isFreshwater;
}
@Override
public void swim() {
if (isFreshwater) {
System.out.println(name + " swims in freshwater");
} else {
System.out.println(name + " swims in saltwater");
}
System.out.println(name + " can swim up to " + age + " mph");
}
}
```
以上三个类分别实现了`Animal`、`Flying`和`Swimming`接口,通过使用循环结构、条件语句和数组结构,实现了不同的操作。`Animal`类中的`eat()`方法使用了循环结构和条件语句,`Animal`类中的`sleep()`方法使用了条件语句,`Bird`类中的`fly()`方法使用了数组结构,`Fish`类中的`swim()`方法使用了条件语句。
阅读全文