[20-05-05][Thinking in Java 10]Java Polymorphism 4 - Downcasting

Posted mirai3usi9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[20-05-05][Thinking in Java 10]Java Polymorphism 4 - Downcasting相关的知识,希望对你有一定的参考价值。

1 package test_2_2;
2 
3 public class Cycle {
4 
5     public void balance() {
6         
7         System.out.println("this is Cycle.balance()");
8     }
9 }

 

 1 package test_2_2;
 2 
 3 public class Bicycle extends Cycle {
 4 
 5     @Override
 6     public void balance() {
 7 
 8         System.out.println("this is Bicycle.balance()");
 9     }
10     
11 }

 

 1 package test_2_2;
 2 
 3 public class Unicycle extends Cycle {
 4 
 5     @Override
 6     public void balance() {
 7 
 8         System.out.println("this is Unicycle.balance()");
 9     }
10 
11 }

 

1 package test_2_2;
2 
3 public class Tricycle extends Cycle{
4 
5 }

 

 1 package test_2_2;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         
 7         /**
 8          * 向上转型
 9          */
10         Cycle[] cycles = {new Unicycle(), new Bicycle(), new Tricycle()};
11 
12         cycles[0].balance();
13         cycles[1].balance();
14         cycles[2].balance();
15         
16         System.out.println("-----");
17         /**
18          * 向下转型
19          */
20         ((Unicycle)cycles[0]).balance();
21         ((Bicycle)cycles[1]).balance();
22         ((Tricycle)cycles[2]).balance();
23 
24     }
25 
26 }

 

结果如下:

this is Unicycle.balance()
this is Bicycle.balance()
this is Cycle.balance()
-----
this is Unicycle.balance()
this is Bicycle.balance()
this is Cycle.balance()

以上是关于[20-05-05][Thinking in Java 10]Java Polymorphism 4 - Downcasting的主要内容,如果未能解决你的问题,请参考以下文章

Thinking In Java

Hacker Rank: Two Strings - thinking in C# 15+ ways

Thinking in Java & Writing in Python

Thinking in LINQ, Chapter 1, Thinking Functionally

Thinking in Java

Thinking in React(翻译)