1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| public class ex1 { public static void main(String[] args) { Dog dog =new Dog("大黄",13,"公"); System.out.println(dog.eat()); dog.prinfo(); Dog dog2 =new Dog("小粉",20,"直升机","草"); System.out.println(dog2.eat()); dog2.prinfo(); } } class animal{ private String name; private int age; private String sex; public animal(String name, int age, String sex) { this.name = name; this.age = age; this.sex = sex; } public void prinfo(){ System.out.println(getName()+"今年"+getAge()+"岁了,是个"+getSex()+"宠物"); return; } private void info(){ System.out.println(getName()+"今年"+getAge()+"岁了,是个"+getSex()+"宠物"); return; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public void setSex(String sex) { this.sex = sex; }
public int getAge() { return age; }
public String getName() { return name; }
public String getSex() { return sex; } } class Dog extends animal{ private String food="骨头"; public Dog(String name, int age, String sex, String food) { super(name, age, sex); this.food = food; } public Dog(String name, int age, String sex) { super(name, age, sex); //这里就使用了多态,通过参数的不同,调用同一个函数名但有不同的效果 } public String eat(){ return food; } } }
|