Java 继承示例:Animal 和 Dog 类输出结果
以下 Java 代码片段演示了继承的概念:
class Animal {
Animal() {
System.out.print ('Animal ');
}
}
class Dog extends Animal {
Dog() {
System.out.print ('Dog ');
}
}
public class Test {
public static void main(String[] args) {
Dog snoppy= new Dog();
}
}
程序执行后,在控制台的输出结果为:Animal Dog
解释:
- 继承关系: Dog 类继承自 Animal 类,意味着 Dog 类拥有 Animal 类的所有属性和方法。
- 构造函数调用: 当创建 Dog 对象
snoppy时,首先会调用 Dog 类的构造函数Dog()。 - 父类构造函数: Dog 类的构造函数隐式地调用了父类 Animal 类的构造函数
Animal(),因此System.out.print('Animal ');会先执行。 - 子类构造函数: 接着执行 Dog 类的构造函数,打印
System.out.print('Dog ');。
最终,程序在控制台输出 'Animal Dog'。
原文地址: https://www.cveoy.top/t/topic/mCus 著作权归作者所有。请勿转载和采集!