1、创建一个Person类,具有name和age,两个成员变量。具有say()方法,可以在屏幕输出 name和age。 2、在Person类中添加构造方法,可以使用 Person p = new Person(tom,29);或 Person p = new Person(tom);形式初始
时间: 2024-02-20 10:00:49 浏览: 86
Python面向对象总结及类与正则表达式详解
化对象,前者同时设置name和age,后者只设置name,age默认为0。实现代码如下:
```java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public void say() {
System.out.println("My name is " + this.name + ", I am " + this.age + " years old.");
}
}
```
使用示例:
```java
Person p1 = new Person("Tom", 29);
p1.say(); // 输出:My name is Tom, I am 29 years old.
Person p2 = new Person("Jerry");
p2.say(); // 输出:My name is Jerry, I am 0 years old.
```
阅读全文