- class TestAnimal {
- public static void main(String[] args) {
- Cat c = new Cat();
- c.setColor("黑色");
- c.setLeg(4);
- System.out.println(c.getColor() + "..." + c.getLeg());
- Dog d = new Dog("蓝色",6);
- System.out.println(d.getColor() + "..." + d.getLeg());
- }
- }
- class Animal {
- private String color; //颜色
- private int leg; //腿的个数
- public Animal(){} //无参构造
- public Animal(String color,int leg) { //带参构造
- this.color = color;
- this.leg = leg;
- }
- public void setColor(String color) { //设置颜色
- this.color = color;
- }
- public String getColor() { //获取颜色
- return color;
- }
- public void setLeg(int leg) { //设置腿个数
- this.leg = leg;
- }
- public int getLeg() { //获取腿个数
- return leg;
- }
- public void eat(){ //吃饭
- System.out.println("吃饭");
- }
- }
- class Cat extends Animal{ //继承动物类
- public Cat(){} //无参构造
- public Cat(String color,int leg) { //带参构造
- super(color,leg); //从父类中获取参数
- }
- public void eat(){ //重写吃饭
- System.out.println("猫吃鱼");
- }
- public void catchMouse() { //抓老鼠
- System.out.println("抓老鼠");
- }
- }
- class Dog extends Animal {
- public Dog(){}
- public Dog(String color,int leg) {
- super(color,leg);
- }
- public void eat(){
- System.out.println("狗吃肉");
- }
- public void lookHome() {
- System.out.println("看家");
- }
- }
复制代码 |
|