创建父类:
1 package org.hanqi.pn0120; 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 org.hanqi.pn0120; 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 25 public static Object getData(int i) 26 { 27 Object rtn = null; 28 //获取数据 29 if (i==1) 30 { 31 //1 father 32 Father f = new Father("向上转型的父类"); 33 //向上转型 34 rtn = f; 35 } 36 else 37 { 38 //2 son 39 Son s = new Son(); 40 rtn = s; 41 } 42 return rtn; 43 } 44 }
创建测试类:
1 package org.hanqi.pn0120; 2 3 public class TestJiCheng { 4 5 public static void main(String[] args) { 6 // 7 Father f = new Father("父亲"); 8 f.setName("父亲"); 9 f.setAge(50); 10 System.out.println("名字是:"+f.getName()+" 年龄是:"+f.getAge()); 11 f.work(); 12 Son s = new Son(); 13 s.setName("儿子"); 14 s.setAge(20); 15 System.out.println("名字是:"+s.getName()+" 年龄是:"+s.getAge()); 16 s.work(); 17 s.sing(); 18 19 System.out.println(); 20 21 //转型 22 //向上转型 子类转成父类 23 Father f1 = new Son(); 24 System.out.println("名字是:"+s.getName()); 25 f1.work();//如果被子类重写,调用子类的方法 26 //f1.sing 若父类想调用子类特有的成员,必须再进行向下转型 27 28 System.out.println("向下转型"); 29 //向下转型 父类转成子类 30 //Son s1 = (Son) new Father("父亲"); 31 Son s1 = (Son) f1; 32 s1.work(); 33 s1.sing(); 34 System.out.println(); 35 36 Father f2 = (Father)Son.getData(1); 37 f2.work(); 38 } 39 }
运行结果为:
总结:
1 package org.hanqi.pn0120; 2 3 public class TestZhuanXing { 4 5 public static void main(String[] args) { 6 7 // 向上转型 8 Object obj = new Son(); 9 //判断某个对象是否是某个类的实例,返回boolean 10 if(obj instanceof Son) 11 { 12 System.out.println("obj是Son的实例"); 13 } 14 15 Father f = new Father(""); 16 17 if(f instanceof Son) 18 { 19 System.out.println("f是Son的实例"); 20 } 21 else 22 { 23 System.out.println("f不是Son的实例"); 24 } 25 if(obj instanceof Father) 26 { 27 System.out.println("boj是Father的实例"); 28 } 29 else 30 { 31 System.out.println("boj不是Father的实例"); 32 } 33 34 //向下转型 35 Son s = (Son)obj; 36 s.work(); 37 s.sing(); 38 Father f1 = (Father)obj; 39 f1.work(); 40 } 41 }
运行结果为:
附思维导图: