使用父类Student声明一个对象变量stu,使用已创建的子类s对象进行赋值,然后使用父类对象stu调用print()方法,结果跟子类对象调用print()是否有区别?为什么? Student stu=s; stu.print();
时间: 2024-05-24 11:15:04 浏览: 8
假设子类为s,如果使用父类声明一个对象变量stu,使用子类对象s进行赋值,那么两者的print()方法调用结果是相同的,因为子类继承了父类的print()方法并且没有对其进行重写,因此它们的方法体是相同的。
因此,使用父类对象stu调用print()方法和使用子类对象s调用print()方法没有区别,都会输出相同的结果。这是因为在面向对象编程中,父类可以引用子类对象,但子类对象也可以直接调用父类方法,这体现了父类与子类之间的继承关系。
相关问题
设计继承上述题目(1)的Student 类的子类Undergraduate。子类Undergraduate不仅具有父类的成员变量name(姓名)、no(学号),还定义新成员变量academy(学院)、department (系);并重载方法void setData(String name,String no, String academy, String department) 用于设置姓名、学号、学院和系;以及重写父类中void print()方法,实现输出姓名、学号、学院和系。在main()方法中创建一个该子类对象s,接着调用相应方法设置一个学生的姓名、学号、学院和系并输出。 (a)编写程序文件 Undergraduate.java,源代码如下: (b)编译运行程序,其结果如下: (c)使用父类Student声明一个对象变量stu,使用已创建的子类s对象进行赋值,然后使用父类对象stu调用print()方法,结果跟子类对象调用print()是否有区别?为什么? Student stu=s; stu.print();
(a) Undergraduate.java文件代码如下:
```java
public class Undergraduate extends Student {
private String academy;
private String department;
public void setData(String name,String no, String academy, String department) {
this.name = name;
this.no = no;
this.academy = academy;
this.department = department;
}
@Override
public void print() {
System.out.println("姓名:" + name);
System.out.println("学号:" + no);
System.out.println("学院:" + academy);
System.out.println("系:" + department);
}
}
```
(b) 编译运行程序,结果如下:
```
姓名:张三
学号:20190001
学院:计算机科学与技术学院
系:软件工程系
```
(c) 使用父类Student声明一个对象变量stu,使用已创建的子类s对象进行赋值,然后使用父类对象stu调用print()方法,结果跟子类对象调用print()是否有区别?为什么?
使用父类Student声明一个对象变量stu,使用已创建的子类s对象进行赋值,可以编译通过。但是在调用print()方法时,由于父类中的print()方法没有被子类重写,所以会调用父类中的print()方法,输出的结果只有姓名和学号,没有学院和系的信息。
因此,使用父类对象stu调用print()方法和使用子类对象调用print()方法是有区别的,因为子类重写了print()方法,所以输出的信息更完整。
定义一个student类的对象stu1的方法
此题目要求定义一个学生类(student),包括姓名、班级、成绩等属性;定义无参构造方法和有参构造方法,完成成员变量的初始化;定义方法getName和setName完成对成员变量“姓名”的设定和获取;定义一个方法输出学生的信息。定以后需要测试类,创建学生类的对象,访问对象的相关信息,完成对所定义的学生类的测试。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)