用java写个类人模型
时间: 2024-03-01 19:50:22 浏览: 54
好的,以下是一个简单的Java类人模型的代码,具有基本的属性和方法:
```java
public class Human {
private String name;
private int age;
private String gender;
private double height;
private double weight;
public Human(String name, int age, String gender, double height, double weight) {
this.name = name;
this.age = age;
this.gender = gender;
this.height = height;
this.weight = weight;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
public double getHeight() {
return height;
}
public double getWeight() {
return weight;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setHeight(double height) {
this.height = height;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void introduce() {
System.out.println("Hi, my name is " + name + ", I am " + age + " years old, " + gender + ", my height is " + height + "cm and my weight is " + weight + "kg.");
}
public double calculateBMI() {
return weight / ((height / 100) * (height / 100));
}
}
```
这个类包含了人的基本属性,如姓名、年龄、性别、身高和体重,以及介绍自己和计算BMI的方法。我们可以在其他类中创建Human对象,并使用它的方法和属性。例如,我们可以这样使用:
```java
public class Main {
public static void main(String[] args) {
Human person = new Human("Tom", 20, "Male", 180, 70);
person.introduce();
System.out.println("My BMI is " + person.calculateBMI());
}
}
```
这里我们创建了一个名为Tom、年龄20岁、身高180cm、体重70kg的男性。然后我们使用introduce方法介绍他自己,并使用calculateBMI方法计算他的BMI。
阅读全文