java面向对象 十二生肖
时间: 2024-02-10 11:41:17 浏览: 29
可以使用Java面向对象的思想来实现一个十二生肖的程序。具体实现方式如下:
1. 定义一个Animal类,包含属性name、age和sex,以及方法eat和sleep。
2. 定义12个子类分别表示十二生肖动物,继承Animal类,并实现各自的属性和方法。
3. 在程序中使用switch语句根据用户输入的年份计算出对应的生肖,并实例化对应的子类对象。
示例代码如下:
Animal类:
```
public class Animal {
protected String name;
protected int age;
protected String sex;
public void eat() {
System.out.println(name + " is eating.");
}
public void sleep() {
System.out.println(name + " is sleeping.");
}
}
```
12个子类:
```
public class Rat extends Animal {
public Rat() {
name = "Rat";
age = 0;
sex = "Unknown";
}
}
public class Ox extends Animal {
public Ox() {
name = "Ox";
age = 0;
sex = "Unknown";
}
}
// 依此类推,实现12个子类
```
主程序:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the year: ");
int year = sc.nextInt();
String[] animals = {"Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
"Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig"};
int index = (year - 1900) % 12;
if (index < 0) {
index += 12;
}
String animalName = animals[index];
System.out.println("The animal of " + year + " is " + animalName);
Animal animal = null;
switch (animalName) {
case "Rat":
animal = new Rat();
break;
case "Ox":
animal = new Ox();
break;
// 依此类推,实例化对应的子类对象
default:
break;
}
if (animal != null) {
animal.eat();
animal.sleep();
}
}
}
```
运行程序后,用户输入年份,程序会计算出对应的生肖,并实例化对应的子类对象,然后调用eat和sleep方法。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)