/*
猫狗案例
动物类: Animal
name, age
eat()
猫类:Cat
playGame()
狗类:Dog
lookHome()
需求: 请 完成 动物类,猫类,狗类的设计,并创建猫、狗的对象,调用方法
创建猫和狗的时候,要求采用构造方法的方式赋值
*/
//动物类
class Animal {
//成员变量
private String name ;
private int age;
//构造方法
public Animal(){}
public Animal(String name, int age){
this.name = name;
this.age = age;
}
//成员方法
public void setName(String name){
//public void setName(){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
//吃饭
public void eat(){
System.out.println("吃饭");
}
}
//狗类
class Dog extends Animal {
//构造方法
public Dog(){}
public Dog(String name, int age){
super(name, age);
}
public void lookHome(){
System.out.println("看家");
}
}
//猫类
class Cat extends Animal {
//构造方法
public Cat(){}
public Cat(String name, int age){
//this.name = name;
//this.age = age;
//super.name = name;
super(name, age);
}
//成员方法
public void playGame(){
System.out.println("打游戏");
}
}
class ExtendsExerciseDemo {
public static void main(String[] args) {
//Cat c = new Cat();
//c.setName("小a");
//System.out.println(c.getName());
Cat c = new Cat("小a", 8);
System.out.println(c.getName() + "--" + c.getAge());
c.eat();
c.playGame();
Dog d = new Dog("小a", 8);
System.out.println(d.getName() + "--" + d.getAge());
d.eat();
d.lookHome();
}
}
|
|