其他分享
首页 > 其他分享> > 面向对象_向下转型_向上转型

面向对象_向下转型_向上转型

作者:互联网

1 package com.msb9;
2 
3 public class Animal {
4     int age;
5     public void shout(){
6         System.out.println("小动物在大声叫");
7     }
8 }
 1 package com.msb9;
 2 
 3 public class Pig extends Animal {
 4     double weight;
 5     public void shout(){
 6         System.out.println("小猪哼哼叫");
 7     }
 8     public void eat(){
 9         System.out.println("吃的比较多");
10     }
11 }
 1 package com.msb9;
 2 
 3 public class Demo {
 4     public static void main(String[] args) {
 5         Pig p = new Pig();
 6         Animal an = p;//转型:向上转型
 7         an.shout();
 8 
 9 
10         //加入转型的代码
11         //将AnimaL转为Pig类型
12         Pig pig = (Pig)an;//转型:向下转型
13 
14         pig.eat();
15         pig.age = 10;
16         pig.weight = 60.4;
17     }
18 }

 

 

 

Pig pig = (Pig)an;//转型:向下转型

 

 

 

标签:msb9,void,转型,pig,面向对象,向下,Pig,public
来源: https://www.cnblogs.com/lcc-lv/p/15755203.html