day12作业-----------------Java面向对象--JavaObject02-3

作业

1. 结合多态发生的条件,及继承相关知识,自己总结并验证下,哪些方法无法实现多态效果。

2. 自己定义一个类,类中定义3个成员变量,这3个成员变量都被final修饰,
请用3种不同方式,为这3个被final修饰的成员变量赋值。

3. 实现如下多态案例,分别定义Person类,SouthPerson(表示南方人),NorthPerson(表示北方人)

Person
eat()

SouthPerson
eat()

NorthPerson
eat()

写代码实现,eat方法的多态效果

1:人要吃饭
2:南方人吃炒菜和米饭
3:北方人吃烩菜和馒头

 

参考答案:

扫描二维码关注公众号,回复: 10951728 查看本文章

1.

 1 package com.day012;
 2 /*
 3  * 1.  结合多态发生的条件,及继承相关知识,自己总结并验证下,哪些方法无法实现多态效果。
 4  
 5  答案:
 6  1. 考虑到多态发生的条件是,
 7    1.继承
 8    2.方法覆盖
 9    3.父类引用指向子类实例
10 所以哪些方法(行为),实现不了多态效果呢?不能在子类中被覆盖的方法
11 a. 父类中的private方法(不能被子类覆盖)
12 b. 父类中的构造方法(不能被子类继承)
13 c. 父类中的静态方法(不能被子类覆盖)
14 d. 父类中被final修饰的方法(不能被子类覆盖)
15 
16  
17  */
18 public class Demo1 {
19 
20 }

2.

 1 package com.day012;
 2 /*
 3  * 2. 自己定义一个类,类中定义3个成员变量,这3个成员变量都被final修饰,
 4    请用3种不同方式,为这3个被final修饰的成员变量赋值。
 5 
 6  */
 7 public class Demo2 {
 8     public static void main(String[] args) {
 9         A nameA = new A();
10         System.out.println("a = "+nameA.a );
11         System.out.println("b = "+nameA.b );
12         System.out.println("c = "+nameA.c );
13     }
14 }
15 class A{
16     //1.在类体中定义成员变量时为 a 赋值(初始化语句)
17     final int a = 1;
18     final int b;
19     final int c;
20     //2.在构造代码块中为 b 赋值
21     {
22         b = 2;
23     }
24     //3.在构造方法中为 c 赋值。注意:要在所有的构造方法中都为 c 赋值。
25     public A() {
26         this.c = 3;
27     }
28 }

运行结果:

3.

 

 1 package com.day012;
 2 /*
 3  * 3. 实现如下多态案例,分别定义Person类,SouthPerson(表示南方人),NorthPerson(表示北方人)
 4 Person
 5   eat()
 6 
 7 SouthPerson
 8    eat()
 9 
10 NorthPerson
11    eat()
12 
13 写代码实现,eat方法的多态效果
14 1:人要吃饭
15 2:南方人吃炒菜和米饭
16 3:北方人吃烩菜和馒头
17  */
18 public class Demo3 {
19     public static void main(String[] args) {
20         Person person = new Person();
21         polymorphism(person);//1:人要吃饭
22         person = new SouthPerson();
23         polymorphism(person);//2:南方人吃炒菜和米饭
24         person = new NorthPerson();
25         polymorphism(person);//3:北方人吃烩菜和馒头
26     }
27     
28     public static void polymorphism(Person person) {
29         person.eat();
30     }
31 }
32 
33 class Person{
34     public void eat() {
35         System.out.println("1:人要吃饭");
36     }
37 }
38 //南方人
39 class SouthPerson extends Person{
40     public void eat() {
41         System.out.println("2:南方人吃炒菜和米饭");
42     }
43 }
44 //北方人
45 class NorthPerson extends Person{
46     public void eat() {
47         System.out.println("3:北方人吃烩菜和馒头");
48     }
49 }

运行结果:

猜你喜欢

转载自www.cnblogs.com/dust2017/p/12731955.html
今日推荐