定义类Human,具有若干属性和功能;定义其子类Man、Woman;
在主类Test中分别创建子类、父类和上转型对象,并测试其特性。
Human:
package eryi; public class Human { 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 void speak() { System.out.println("我是小孩"); } }
Man:
package eryi; public class Man extends Human { public void speak() { System.out.println("我是男生"); } }
Woman:
package eryi; public class Woman extends Human { public void speak() { System.out.println("我是女生"); } }
Human1:
package eryi; public class Human1 { public static void main(String[] args) { // TODO 自动生成的方法存根 Human h=new Man(); h.setAge(18); h.setName("姓名:张三。"); h.speak(); System.out.println(h.getName()+"年龄:"+h.getAge()); Human h1=new Woman(); h1.setAge(16); h1.setName("姓名:静静。"); h1.speak(); System.out.println(h1.getName()+"年龄:"+h1.getAge()); } }
编写一个Animal类,具有属性:种类;具有功能:吃、睡。定义其子类Fish
和Dog,定义主类E,在其main方法中分别创建其对象并测试对象的特性。
Animal:
package eryi; public class Animal { private String zhonglei; private String name; public String getZhonglei() { return zhonglei; } public void setZhonglei(String zhonglei) { this.zhonglei = zhonglei; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void eat() { } public void sleep() { } }
Dog:
package eryi; public class Dog extends Animal{ public void eat() { System.out.println("我喜欢吃肉"); } public void sleep() { System.out.println("我喜欢睡懒觉"); } }
Fish:
package eryi; public class Fish extends Animal{ public void eat() { System.out.println("我喜欢吃鱼食"); } public void sleep() { System.out.println("我喜欢早起"); } }
测试:
package eryi; public class Animal1 { public static void main(String[] args) { // TODO 自动生成的方法存根 Dog d=new Dog(); d.setName("啾啾"); d.setZhonglei("博美"); System.out.println("我是一只"+d.getZhonglei()+".我的名字是"+d.getName()); d.eat(); d.sleep(); Fish f=new Fish(); f.setName("尼莫"); f.setZhonglei("小丑鱼"); System.out.println("我是一只"+f.getZhonglei()+".我的名字是"+f.getName()); f.eat(); f.sleep(); } }
时间: 2024-10-10 16:33:08