Java动态类示例:创建不同学生的实例
{"title":"Java动态类示例:创建不同学生的实例","description":"本示例展示了如何在Java中使用类来表示不同学生的实例。通过定义Student类,我们可以创建多个学生实例,每个实例都有不同的姓名和年龄。","keywords":"Java, 动态类, 类实例, 学生实例, 姓名, 年龄","content":"\u003ccode\u003ejava\npublic class Student {\n private String name;\n private int age;\n\n public Student(String name, int age) {\n this.name = name;\n this.age = age;\n }\n\n public void display() {\n System.out.println("姓名:" + name);\n System.out.println("年龄:" + age);\n }\n\n public static void main(String[] args) {\n // 创建不同的学生实例\n Student student1 = new Student("张三", 18);\n Student student2 = new Student("李四", 20);\n Student student3 = new Student("王五", 22);\n\n // 调用display方法显示学生信息\n student1.display();\n student2.display();\n student3.display();\n }\n}\n\u003c/code\u003e\n在上面的示例中,我们定义了一个Student类,它有两个参数:姓名和年龄。在构造方法中,我们将传入的参数赋值给类的成员变量。还定义了一个display方法用于显示学生的姓名和年龄。\n\n在main方法中,我们通过new关键字创建了不同的学生实例。然后,通过调用display方法来显示每个学生的信息。\n\n你可以根据需要创建任意数量的学生实例,并为每个实例提供不同的姓名和年龄参数。"}
原文地址: https://www.cveoy.top/t/topic/pBWp 著作权归作者所有。请勿转载和采集!