/javaDemo4/src/com/imooc/Animal.java
package com.imooc; public class Animal { }
/javaDemo4/src/com/imooc/Dog.java
package com.imooc; public class Dog extends Animal { }
/javaDemo4/src/com/imooc/Initail.java
package com.imooc; public class Initail { public static void main(String[] args) { Animal obj1 = new Animal(); Animal obj2 = new Dog(); //父类的引用是可以指向子类对象 //Dog obj3 = new Animal(); //报错 } }
/javaDemo4/src/com/imooc/Animal.java
package com.imooc; public class Animal { public void eat() { System.out.print("动物具有吃的能力"); } }
/javaDemo4/src/com/imooc/Dog.java
package com.imooc; public class Dog extends Animal { public void eat() { System.out.print("狗具有吃肉的能力"); } public void watchDoor() { System.out.print("狗具有看门的能力"); } }
/javaDemo4/src/com/imooc/Initail.java
package com.imooc; public class Initail { public static void main(String[] args) { // TODO Auto-generated method stub Animal obj1 = new Animal(); Animal obj2 = new Dog(); //父类的引用是可以指向子类对象 //Dog obj3 = new Animal(); //报错 Animal obj3 = new Cat(); obj1.eat(); obj2.eat(); obj3.eat(); // obj2.watchDoor(); } }