下面是一个简单的 Java 继承的实例:

// 父类 Animal
class Animal {
    public void move() {
        System.out.println('动物可以移动');
    }
}

// 子类 Dog
class Dog extends Animal {
    public void move() {
        System.out.println('狗可以跑和走');
    }
}

// 子类 Cat
class Cat extends Animal {
    public void move() {
        System.out.println('猫可以跳和爬');
    }
}

// 测试类
public class Test {
    public static void main(String[] args) {
        Animal animal = new Animal();
        Dog dog = new Dog();
        Cat cat = new Cat();
        
        animal.move();
        dog.move();
        cat.move();
    }
}

在上面的例子中,Animal 是父类,而 Dog 和 Cat 是子类。子类继承了父类的属性和方法,并且可以重写父类的方法。在测试类中,我们可以创建 Animal、Dog 和 Cat 的对象,并且调用它们的 move() 方法,得到不同的输出结果。

Java 继承实例:动物、狗和猫

原文地址: https://www.cveoy.top/t/topic/nErL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录