java实验三多态性_实验五Java的类及多态性

41528d3028836879cd698677c3999917.gif实验五Java的类及多态性

实验五 Java的类及多态性 一、实验目的: 1. 掌握Java类及多态性的含义。 2. 掌握instanceof的使用方法。 3. 掌握应用变量的转换。 二、实验要求: 编写一个能体现多态性的Java应用程序。 三、实验内容: (1)类 1、常量的声明 :声明一个常量PI,编译它,查看有何错误并修改。 错误: class Point { int x,y; static int z; final double PI=3.1415926; [修改:赋值3.1415926] Point(int a,int b) { x=a; y=b; } Point() { this(1,1); } static void output() { System.out.println(“output() called“); System.out.println(z); } void output(int a,int y) { output(); z=5; this.x=x; this.y=y; } public static void main(String [] args) { Point pt1=new Point(); Point pt2=new Point(); pt1.z=5; pt2.z=6; System.out.println(pt1.z); } } 2、声明一个静态的常量:修改上题的前半部分,如下。编译,查看有何错误,并修改 错误: class Point { int x,y; static int z; final double PI ; [修改:删除static。] Point(int a,int b) { PI=3.1415926; x=a; y=b; } Point() { this(1,1); } static void output() { System.out.println(“output() called“); System.out.println(z); } void output(int a,int y) { output(); z=5; this.x=x; this.y=y; } public static void main(String [] args) { Point pt1=new Point(); Point pt2=new Point(); pt1.z=5; pt2.z=6; System.out.println(pt1.z); } } 3、继承:新建一个Animal.java文件,并编译它。查看源文件的当前目录下生成了几个类文件,并选择一个执行它,输出结果。 class Animal { int height,weight; void eat() { System.out.println(“animal eat“); } void sleep() { System.out.println(“animal sleep“); } void breathe() { System.out.println(“animal breathe“); } } class Fish extends Animal { } class Integration { public static void main(String[] args) { Animal an=new Animal(); Fish fh=new Fish(); an.breathe(); fh.height=30; fh.breathe(); } } 4、修改上题中的class Fish extends Animal类,如下,并执行它,查看结果。 class Fish extends Animal { void breathe() { System.out.println(“animal bubble“); } } 5、再次修改class Fish extends Animal类和Integration类,如下,并执行,查看结果。并思考课件中对于super的说明。 class Animal { int height,weight; void eat() { System.out.println(“animal eat“); } void sleep() { System.out.println(“animal sleep“); } void breathe() { System.out.println(“animal breathe“); } } class Fish extends Animal { int height; void breathe() { super.breathe(); super.height=40; System.out.println(“fish bubble“); } } class Integration { public static void main(String[] args) { //Animal an=new Animal(); Fish fh=new Fish(); //an.breathe(); fh.height=30; fh.breathe(); } } Super 用法: o 提供了对父类的访问。 o 可以使用super访问父类被子类隐藏的变量或覆盖的方法。 6、分别在Animal类和Fish类中,添加构造方法如下: 并将Integration类,修改如下 class Animal { int height,weight; void eat() { System.out.println(“animal eat“); } void sleep() { System.out.println(“animal sleep“); } void breathe() { System.out.pr

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值