多态和类型转换

1、多态是方法的多态,属性没有多态。

2、父类与子类,有联系,类型转换异常。

3、存在条件:继承关系, 方法需要重写,父类引用指向子类对象。

 

例子:

 1 public class Polymorphism {
 2     public static void main(String[] args) {
 3 
 4         //Student2能调用的方法都是自己的或者继承父类的
 5         Student2 s1 = new Student2();
 6         //父类的引用指向子类
 7         //Person2父类型, 可以指向子类,但是不能调用子类独有的方法
 8         Person2 s2 = new Student2();
 9 
10         s1.run();
11         s2.run();
12 
13         s1.eat();
14         //对象能执行哪些方法,主要看对象左边的类型,和右边关系不大
15         //子类重写了父类方法,执行子类的方法
16         ((Student2)s2).eat();
17     }
18 }
19 class Person2 {
20     public void run() {
21         System.out.println("run");
22     }
23 }
24 class Student2 extends Person2{
25     @Override
26     public void run() {
27         System.out.println("son");
28     }
29     public void eat(){
30         System.out.println("eat");
31     }
32 
33 }

 

类型转换

1、父类引用指向子类的对象。

2、把子类转换为父类,向上转换。

3、把父类转换为子类,向下转换,强制转换。

4、方便方法的调用,减少重复的代码!简洁

 

例子:

 1 public class Convert {
 2     public static void main(String[] args) {
 3         //类型之间的转换
 4         Person3 obj = new Student3();
 5         //obj将这个对象转换为Student3类型, 我们就可以使用Student3类型的方法了!
 6         //强制转换, 高转低!
 7         //或者我们可以使用一句来代替两句: ((Student3)obj).go();
 8         Student3 obj1 = (Student3) obj;
 9         obj1.go();
10 
11         //子类转化为父类,可能丢失自己本来的一些方法!
12         Student3 student3 = new Student3();
13         student3.run();
14         //转换为Person3类型,低转高,自动转
15         Person3 person3 = student3;
16     }
17 
18 }
19 class Person3{
20 
21 }
22 
23 class Student3 extends Person3{
24     public void go(){
25         System.out.println("go");
26     }
27 
28     public void run(){
29         System.out.println("run");
30     }
31 
32 }

 

posted @ 2022-03-10 15:51  小王同学学编程  阅读(79)  评论(0)    收藏  举报
levels of contents