046_面向对象_19_内存分析
一、关于多态的演示示例
package edu.aeon.test; /** * [说明]:动物类 * @author aeon * */ public class Animal { String str; public void voice() { System.out.println("普通动物叫声!"); } } class Cat extends Animal { public void voice() { System.out.println("喵喵喵"); } public void catchMouse() { System.out.println("抓老鼠"); } } class Dog extends Animal { public void voice() { System.out.println("汪汪汪"); } public void seeDoor() { System.out.println("看门!"); } } class Tiger extends Animal { public void voice() { System.out.println("哇哇哇"); } } class Pig extends Animal { public void voice() { System.out.println("哼哼哼"); } }
package edu.aeon.test; /** * [说明]:测试多态 * @author aeon * */ public class Test { public static void testAnimalVoice(Animal c) { c.voice(); if (c instanceof Cat) { ((Cat) c).catchMouse(); } } public static void main(String[] args) { Animal a = new Cat(); Cat a2 = (Cat) a; testAnimalVoice(a); } }
该示例在内存中的结构图如下:
运行结果截图: