1.掌握Java中类的创建。 2.掌握Java中实例化对象。 3.掌握对属性和方法的引用。 4.把课堂上学到的理论用于实践,并验证理论的正确性,和发现新的问题。 实验内容 1.创建Person类,①具有属性name、age、sex
时间: 2024-06-11 08:07:21 浏览: 132
Java的类和对象实验.pdf
、height和weight;②具有方法eat()和sleep()。 2.创建Student类,继承Person类,①新增属性school和grade;②新增方法study()和doHomework()。 3.在主函数中实例化一个Person对象和一个Student对象,并分别调用它们的属性和方法。 4.验证理论并发现新的问题,比如如果Person类中的属性age被设置为private,那么在Student类中是否可以直接访问它?如果不能,应该怎么做? 实验步骤 1.创建Person类,并定义它的属性和方法。代码如下: public class Person { private String name; private int age; private String sex; private double height; private double weight; public void eat() { System.out.println("I'm eating now."); } public void sleep() { System.out.println("I'm sleeping now."); } } 2.创建Student类,继承Person类,并新增它的属性和方法。代码如下: public class Student extends Person { private String school; private int grade; public void study() { System.out.println("I'm studying now."); } public void doHomework() { System.out.println("I'm doing my homework now."); } } 3.在主函数中实例化一个Person对象和一个Student对象,并分别调用它们的属性和方法。代码如下: public static void main(String[] args) { Person person = new Person(); person.name = "Tom"; person.age = 20; person.sex = "male"; person.height = 1.75; person.weight = 65.0; person.eat(); person.sleep(); Student student = new Student(); student.name = "Lily"; student.age = 18; student.sex = "female"; student.height = 1.65; student.weight = 50.0; student.school = "ABC School"; student.grade = 3; student.eat(); student.sleep(); student.study(); student.doHomework(); } 运行结果如下: I'm eating now. I'm sleeping now. I'm eating now. I'm sleeping now. I'm studying now. I'm doing my homework now. 4.验证理论并发现新的问题。 如果在Person类中的属性age被设置为private,那么在Student类中是不能直接访问它的。为了能够访问它,我们可以新增一个public方法getAge()来获取它的值,如下所示: public class Person { private String name; private int age; private String sex; private double height; private double weight; public void eat() { System.out.println("I'm eating now."); } public void sleep() { System.out.println("I'm sleeping now."); } public int getAge() { return age; } } 然后在Student类中就可以通过调用getAge()方法来获取Person类中的私有属性age的值了。
阅读全文