定义类与创建对象(Java)

定义一个类Person,定义nameage属性,定义有参的构造方法对nameage进行初始化。在测试类中创建该类的2个对象,姓名、年龄分别为lili、19lucy、20,在屏幕打印出2个对象的姓名和年龄。

输入格式:
本题目无输入

输出样例:
在这里给出相应的输出。例如:
this person is lili,her age is 19
this person is lucy,her age is 20

public class Main  {
    
    
    public static void main(String[] args) {
    
    
        Person p1=new Person("lili", 19);
        Person p2=new Person("lucy", 20);
        System.out.println("this person is "+p1.name+",her age is "+p1.age);
        System.out.println("this person is "+p2.name+",her age is "+p2.age);
    }
}
class Person {
    
    
    String name;
    int age;

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_51430516/article/details/115120215