定义类Human,具有若干属性和功能;定义其子类Man、Woman; 在主类Test中分别创建子类、父类和上转型对象,并测试其特性。
父类:
package com.lianxi3; public class Human { private String speak; private String jump; public String getSpeak() { return speak; } public void setSpeak(String speak) { this.speak = speak; } public String getJump() { return jump; } public void setJump(String jump) { this.jump = jump; } public Human(String speak, String jump) { super(); this.speak = speak; this.jump = jump; } public Human() { super(); } public void Jump() { System.out.println("跳:"+jump); } public void Speak() { System.out.println("说:"+speak); } public void as() { System.out.println("我能工作"); } }
子类:
package com.lianxi3; public class Man extends Human { private String shui; public String getShui() { return shui; } public void setShui(String shui) { this.shui = shui; } public void Shui() { System.out.println("睡"+shui); } }
测试:
package com.lianxi3; public class Test { public static void main(String[] args) { Man m=new Man(); m.setJump("低"); m.setShui("长"); m.setSpeak("粗"); System.out.println("声音:"+m.getSpeak()+" 跳:"+m.getJump()+" 睡:"+m.getShui()); //向上转型 Human h=new Man(); h.as(); //如果方法被重写,则调用子类的函数 //向下转型 Object ob=new Man();//先转形成等级最高的object Man ma=(Man)ob; //在转型所需要的类型 } }