1 package com.work; 2 3 public class father { 4 5 private String name; 6 private int age; 7 public String getName() { 8 return name; 9 } 10 public void setName(String name) { 11 this.name = name; 12 } 13 public int getAge() { 14 return age; 15 } 16 public void setAge(int age) { 17 this.age = age; 18 } 19 20 // public Father() 21 // { 22 // System.out.println("父类的构造方法"); 23 // } 24 public father (String name) 25 { 26 System.out.println("父类的有参的构造方法"); 27 this.name = name; 28 } 29 //工作 30 public void work() 31 { 32 System.out.println("我劳动我光荣"); 33 } 34 }
1 package com.work; 2 3 public class Son extends father { 4 //Object a;所有类的父类 5 6 public Son() 7 { 8 //super 表示父类 9 super("儿子"); 10 System.out.println("子类的构造方法"); 11 } 12 public void sing() 13 { 14 System.out.println("我喜欢唱歌"); 15 } 16 //覆盖(重写) 17 public void work() 18 { 19 //调用父类的方法 20 //super.work(); 21 //System.out.println("我不喜欢上班,我要去参加海选"); 22 System.out.println("我边上班边练歌"); 23 } 24 public static Object getData(int i) 25 { 26 Object rtn = null; 27 //获取数据 28 if (i==1) 29 { 30 //1 father 31 father f = new father("向上转型的父类"); 32 //向上转型 33 rtn = f; 34 } 35 else 36 { 37 //2 son 38 Son s = new Son(); 39 rtn = s; 40 } 41 return rtn; 42 } 43 }
1 package com.work; 2 3 public class testjicheng { 4 5 public static void main(String[] args) { 6 // 7 father f = new father("父亲"); 8 9 f.setName("父亲"); 10 11 f.setAge(50); 12 13 System.out.println("名字是:"+f.getName()+" 年龄是:"+f.getAge()); 14 15 f.work(); 16 17 Son s = new Son(); 18 19 s.setName("儿子"); 20 21 s.setAge(20); 22 23 System.out.println("名字是:"+s.getName()+" 年龄是:"+s.getAge()); 24 25 s.work(); 26 27 s.sing(); 28 29 System.out.println(); 30 31 //转型 32 33 //向上转型 子类转成父类 34 35 father f1 = new Son(); 36 37 System.out.println("名字是:"+s.getName()); 38 39 f1.work(); //如果被子类重写了,调用子类的方法 40 41 System.out.println("向下转型"); 42 43 //向下转型 父类转成子类 44 45 //Son s1 = (Son) new Father("父亲"); 46 47 Son s1 = (Son) f1; 48 49 s1.work(); 50 51 System.out.println(); 52 53 father f2 = (father)Son.getData(1); 54 55 f2.work(); 56 } 57 }