定义类Human,具有若干属性和功能;定义其子类Man、Woman;
在主类Test中分别创建子类、父类和上转型对象,并测试其特性。
package T092204; public class Human { private String name; private int age; private String sex; 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 String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public void speak(){ System.out.println("I am a human."); } public void run(){ System.out.println("I can run."); } public void getInfo(){ System.out.println("我的名字是:"+getName()+" 我的年龄是:"+getAge()+" 我的性别是:"+getSex()); Man m=new Man(); } } package T092204; public class Man extends Human { public void man(){ if(getSex()=="男") { System.out.println("我是男人"); } else{ System.out.println("我是女人"); } } public void run(){ System.out.println("我会打篮球"); } } package T092204; public class Woman extends Human { public void woman(){ if(getSex()=="女") { System.out.println("我是女人"); } else { System.out.println("我是男人"); } } public void run(){ System.out.println("我会跳舞"); } } package T092204; public class Test { public static void main(String[] agrs){ Man m=new Man(); m.setName("张三"); m.setAge(30); m.setSex("男"); m.getInfo(); m.speak(); m.run(); m.man(); Human h=new Woman(); h.setName("如花"); h.setAge(25); h.setSex("女"); h.speak(); h.run(); h.getInfo(); if(h instanceof Woman){ Woman w=(Woman)h; w.woman(); } else{ System.out.println("类型不符!"); } } }
时间: 2024-11-05 03:51:00