Java子类继承父类

1.定义标准的猫类和狗类

2.使用继承和方法重写改写代码并测试。

猫类:名字,年龄,shout(){喵喵喵},catchMouse(){}

狗类:名字,年龄,shout(){汪汪汪},watchDoor(){}

一、第一步需要先创建父类animal

public 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) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
    public abstract void shout();
   }

二、分别创建子类Dog 和 Cat

1.Dog

public class Dog extends animal{
    @Override
    public void shout(){
        System.out.println("汪汪汪");
    }

    public void watchDoor(){
        System.out.println("看门");
    }
}

2.Cat

@Override
    public void shout(){
        System.out.println("喵喵喵");
    }
    public void watchDoor(){
        System.out.println("捉老鼠");
    }
}

三、创建一个test输出结果

public class test {
    public static void main(String[] ages){
            Dog  dog = new Dog();
            dog.setName("柯基");
            dog.setAge(1);
            dog.show();
            dog.shout();
            dog.watchDoor();
            System.out.println("----------------------------------------");
            Cat cat = new Cat();
            cat.setName("英短");
            cat.setAge(2);
            cat.show();
            cat.shout();
            cat.catchMouse();
    }
}

Java子类继承父类_第1张图片

 

你可能感兴趣的:(java,开发语言,intellij,idea)