Father类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
package juxing;public class Father { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } //默认构造方法// public Father()// {// System.out.println("父类的构造方法");// } public Father(String name) { System.out.println("父类的有参构造方法"); this.name=name; } public void work() { System.out.println("我劳动我光荣"); } }
Son类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
package juxing;public class Son extends Father {//一个子类智能继承一个父类。单继承 //子类可以扩展父类,自动具有父类的成员 public Son() { //不能在前边加代码,必须先有父类。 super("儿子"); System.out.println("子类的构造方法"); } public void sing() { System.out.println("爱唱歌"); } //子类覆盖,重写。名字一样,参数一致。否则只是扩展 public void work() { //不全覆盖,调用父类的work //super.work(); //System.out.println("我不想去上班,我要参加海选"); System.out.println("边上班边唱歌"); } public static Object getDate(int i)//Object,所有类的父类,都向上转 { Object rtn=null; //获取数据 if(i==1) { //1,father Father f=new Father("向上转型的父类"); //向上转 rtn=f; } else { //2,Son Son s=new Son(); rtn=s; } return rtn; }}
Testjicheng类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
package juxing;public class TestJiCheng { public static void main(String[] args) { Father f=new Father("父亲"); //f.setName("父亲"); f.setAge(50); f.work(); System.out.println(); Son s=new Son(); //s.setName("儿子"); s.setAge(20); System.out.println("儿子"+s.getAge()+"岁"); System.out.println(); s.work(); s.sing(); System.out.println(); System.out.println(); //转型 //向上转型,子类到父类 Father f1=new Son(); System.out.println("名字"+s.getName()); f1.work();//调用子类的work System.out.println(); System.out.println("向下转型,父类转子类"); //向下转型,父类转子类 //Son s1=(Son) new Father("父亲");子类有的父类不一定有 Son s1=(Son)f1; s1.work(); System.out.println(); //调用, System.out.println("类型不确定,用Object,先向上全部转成父类,再向下转型。"); Father f2=(Father)Son.getDate(2); f2.work(); }}