Java--父类的引用指向子类的对象详解!
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java--父类的引用指向子类的对象详解!相关的知识,希望对你有一定的参考价值。
例:
第一步.创建一个Person类
package com.maya.ball; public class Person { private int age; private String name; public Person(int age,String name){ this.age = age; this.name = name; } public void speak(){ } public int getAge(){ return age; } public void setAge(int age){ this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
第二步.创建American类继承Person类。
package com.maya.basketball; import com.maya.ball.Person; public class American extends Person { public double height;-----------------------------新增成员变量 public American(int age,String name,double height){ super(age, name); this.height = height; } public void speak(){ System.out.println("我年龄:"+ this.getAge() +",我叫:"+getName()+",我身高:"+height); } }
第三步.创建Chinese类,同意继承Person类
package com.maya.football; import com.maya.ball.Person; public class Chinese extends Person{ private String sex;-------------------新增成员变量 public Chinese(int age, String name,String sex) { super(age, name); this.sex = sex; } public void speak(){ System.out.println("我年龄:"+ getAge() +",我叫:"+ this.getName() +",我性别:"+sex); } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
第四步.创建Test1类,通过show方法把Person的对象作为参数传进去
package com.maya.test; import com.maya.ball.Person; import com.maya.basketball.American; import com.maya.football.Chinese; public class Test1 { public void show(Person per){ if(per instanceof American){ American am = (American) per; System.out.println(am.height); } if(per instanceof Chinese){ Chinese ch = (Chinese) per; System.out.println(ch.getSex()); } } }
第五步.创建Main方法进行调用
package com.maya.test; import com.maya.ball.Person; import com.maya.basketball.American; import com.maya.football.Chinese; public class Main1 { public static void main(String[] args){ Person per = new American(32,"小明",175); American american = (American) per; double s = american.height; System.out.println(s); Person ame = new American(32,"小明",180); ame.speak(); Person chinese = new Chinese(23,"小李","女"); chinese.speak(); Test1 t = new Test1(); t.show(ame); t.show(chinese); } }
以上是关于Java--父类的引用指向子类的对象详解!的主要内容,如果未能解决你的问题,请参考以下文章