请参看下面的程序:
- public class MyPerson{
- String name;
- int age;
- MyPerson(String name){
- this.name = name;
- this.age = 18;
- }
- MyPerson(String name,int age){
- this(name); // this的第二个作用
- this.age = age;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- public static void main(String[] args){
- MyPerson person1 = new MyPerson("XiaoMing");
- MyPerson person2 = new MyPerson("XiaoLi",36);
- System.out.println("person1 is " + person1.getName());
- System.out.println("person1's age is " + person1.getAge());
- System.out.println("person2 is " + person2.getName());
- System.out.println("person2's age is " + person2.getAge());
- }
- }
复制代码 |