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;//转型:向下转型