使用java 写一个面向对象类,类里的成员属性有id,name,age。成员方法:①通过ID查询信息(name和age)②通过ID查age+1,注意代码规范
时间: 2023-10-03 21:03:55 浏览: 55
好的,以下是Java代码实现:
```java
public class Person {
private int id;
private String name;
private int age;
// 构造方法
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
// 通过ID查询信息(name和age)
public void getInfoById(int id) {
if (this.id == id) {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
} else {
System.out.println("Person not found with ID: " + id);
}
}
// 通过ID查age+1
public void getAgePlusOneById(int id) {
if (this.id == id) {
System.out.println("Age plus one: " + (age + 1));
} else {
System.out.println("Person not found with ID: " + id);
}
}
}
```
使用示例:
```java
public static void main(String[] args) {
Person person = new Person(1, "Tom", 20);
person.getInfoById(1); // 输出:Name: Tom,Age: 20
person.getAgePlusOneById(1); // 输出:Age plus one: 21
}
```
阅读全文