标签:void ping 根据 err span 参数 类的方法 [] ide
1 class Man extends Human{
2 //覆写override
3 public void sleep(){
4 System.out.println("man is sleeping");
5 }
6 public void speak(){
7 System.out.println("i am a man");
8 }
9 }
10 class Woman extends Human{
11 //覆写override
12 public void sleep(){
13 System.out.println("woman is sleeping");
14 }
15 public void speak(){
16 System.out.println("i am a woman");
17 }
18 }
19 public class Human{
20 public void sleep(){
21 System.out.println("human is sleeping");
22 }
23 public static void main(String args[]){
24 Human h = new Man(); //向上转型
25 h.sleep();
26 Man m = new Man();
27 m.sleep();
28 h.speak();
29 }
30 }
实例化子类对象再向上转型成父类,父类对象在调用被子类覆写过的方法时,即是调用子类覆写过的方法,但这个对象在调用子类特有(父类没有)的方法时编译会出错。
1 class Car{
2 public void run(){
3 System.out.println("父类的run方法");
4 }
5 public void speed(){
6 System.out.println("speed:0");
7 }
8 }
9 class Bmw extends Car{
10 public void run(){
11 System.out.println("子类Bmw的run方法");
12 }
13 public void speed(){
14 System.out.println("子类Bmw的speed:100");
15 }
16 }
17 class Benz extends Car{
18 public void run(){
19 System.out.println("子类Benz的run方法");
20 }
21 public void speed(){
22 System.out.println("子类Benz的speed:120");
23 }
24 }
25 class Civic extends Car{
26 public void run(){
27 System.out.println("子类Civic的run方法");
28 }
29 public void speed(){
30 System.out.println("子类Civic的speed:200");
31 }
32 }
33 public class Testdemo1{
34 public static void main(String args[]){
35 show(new Bmw()); //向上转型
36 show(new Benz());
37 show(new Civic());
38 }
39 public static void show(Car c){ //父类实例作为参数
40 c.run();
41 c.speed();
42 }
43 }
通过向上转型实现每个子类具体的功能,如果不用向上转型的这个函数那么需要分别去调用每个子类的每个方法,如下:
1 class Car{
2 public void run(){
3 System.out.println("父类的run方法");
4 }
5 public void speed(){
6 System.out.println("speed:0");
7 }
8 }
9 class Bmw extends Car{
10 public void run(){
11 System.out.println("子类Bmw的run方法");
12 }
13 public void speed(){
14 System.out.println("子类Bmw的speed:100");
15 }
16 }
17 class Benz extends Car{
18 public void run(){
19 System.out.println("子类Benz的run方法");
20 }
21 public void speed(){
22 System.out.println("子类Benz的speed:120");
23 }
24 }
25 class Civic extends Car{
26 public void run(){
27 System.out.println("子类Civic的run方法");
28 }
29 public void speed(){
30 System.out.println("子类Civic的speed:200");
31 }
32 }
33 public class Testdemo2{
34 public static void main(String args[]){
35 show(new Bmw());
36 show(new Benz());
37 show(new Civic());
38 }
39 /*以下用到了方法重载overloading,根据参数来选择重载的方法*/
40 public static void show(Benz c){
41 c.run();
42 c.speed();
43 }
44 public static void show(Bmw c){
45 c.run();
46 c.speed();
47 }
48 public static void show(Civic c){
49 c.run();
50 c.speed();
51 }
52 }
这样提高了代码的简洁性。一旦向上转型了,当需要用到子类的方法时,就需要向下转型
标签:void ping 根据 err span 参数 类的方法 [] ide
原文地址:https://www.cnblogs.com/wang-swjtu/p/10265913.html