java面向对象之父类的引用指向子类的对象
1 package Text; 2 3 public class Job { 4 public void dowork(){ 5 6 } 7 }
1 package Text; 2 3 public class Luosidao extends Job{ 4 public void dowork(){ 5 System.out.println("螺丝刀拧螺丝。。。"); 6 } 7 }
1 package Text; 2 3 public class Chanzi extends Job{ 4 5 @Override 6 public void dowork() { 7 System.out.println("铲子铲土。。。"); 8 } 9 10 public void test(){ 11 System.out.println("测试方法"); 12 } 13 }
1 package Tool; 2 3 import Text.Chanzi; 4 import Text.Job; 5 import Text.Luosidao; 6 7 public class Tool3 { 8 public static void main(String[] args) { 9 Job a =new Luosidao(); 10 Job b =new Chanzi(); 11 a.dowork(); 12 b.dowork(); 13 Chanzi c =(Chanzi)b;//无法调用子类方法,所以强转 14 c.test(); 15 } 16 }