10.2.2 覆盖的应用
【实例10.4】通过下面一个实例,来学习覆盖的应用。
01 public class student2
02 {
03 void print()
04 {
05 System.out.println("这是小明的同学");
06 }
07 public static void main(String[]args)
08 {
09 student2 st=new student2();
10 student3 st1=new student3();
11 st.print();
12 st1.print();
13 }
14 }
15 class student3 extends student2
16 {
17 void print()
18 {
19 System.out.println("这是小明的同学1");
20 System.out.println("他很优秀的");
21 }
22 }
【代码说明】从上面的程序可以看出,子类重新定义了父类的“print()”方法。子类的覆盖方法与父类相同,只是方法体不一样。
【运行效果】
这是小明的同学
这是小明的同学1
他很优秀的