面向对象编程是一种编程范例,它将现实世界的实体抽象为类和对象。类定义了对象的属性和行为,而对象是类的实例,具有特定的状态和行为。
// 创建一个名为 Person 的类
class Person {// 属性private String name;private int age;// 构造函数public Person(String name, int age) {this.name = name;this.age = age;}// 方法public String getName() {return name;}public int getAge() {return age;}
}// 创建 Person 的子类 Student
class Student extends Person {// 额外的属性private String studentID;// 带有额外的参数的构造函数public Student(String name, int age, String studentID) {super(name, age);this.studentID = studentID;}// 额外的方法public String getStudentID() {return studentID;}
}// 创建一个 Person 对象
Person person = new Person("John Doe", 25);// 创建一个 Student 对象
Student student = new Student("Jane Doe", 22, "123456");// 使用对象
System.out.println(person.getName()); // 输出:John Doe
System.out.println(student.getName()); // 输出:Jane Doe
System.out.println(student.getStudentID()); // 输出:123456
本文地址:https://www.badfl.com/article/bce1c0d57394f5710995.html