继承类的Java对象创建
在Java中,构造函数负责特定类的对象创建。除构造函数的其他功能外,它还实例化其类的属性/实例。在Java中,默认情况下,super()方法用作每个类的构造函数的第一行,此处此方法的目的是调用其父类的构造函数,以便在子类继承并使用它们之前很好地实例化其父类的属性。
这里要记住的一点是创建对象时会调用构造函数,但并非必须要在每次调用类的构造函数时都创建该类的对象。在上述情况下,从构造函数中调用parent的construcotr子类的子类,但仅创建子类的对象,因为子类与它的父类处于is-关系。
示例
class InheritanceObjectCreationParent {
public InheritanceObjectCreationParent() {
System.out.println("parent class constructor called..");
System.out.println(this.getClass().getName()); //to know the class of which object is created.
}
}
public class InheritanceObjectCreation extends InheritanceObjectCreationParent {
public InheritanceObjectCreation() {
//here we do not explicitly call super() method but at runtime complier call parent class constructor
//by adding super() method at first line of this constructor.
System.out.println("subclass constructor called..");
System.out.println(this.getClass().getName()); //to know the class of which object is created.
}
public static void main(String[] args) {
InheritanceObjectCreation obj = new InheritanceObjectCreation(); // object creation.
}
}输出结果
parent class constructor called.. InheritanceObjectCreation subclass constructor called.. InheritanceObjectCreation
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下