java父类的构造方法和子类的构造方法
时间: 2023-09-01 19:08:40 浏览: 96
在Java中,子类构造方法默认会调用父类的无参构造方法,如果父类没有无参构造方法,则必须在子类的构造方法中显式调用父类的有参构造方法,传入相应的参数。这一过程可以使用super关键字来实现。例如:
```java
public class ParentClass {
public ParentClass(int arg) {
// 父类有参构造方法
}
}
public class ChildClass extends ParentClass {
public ChildClass(int arg) {
super(arg); // 调用父类有参构造方法
// 子类构造方法
}
}
```
需要注意的是,如果子类中没有显式调用父类的构造方法,Java编译器会自动在子类的构造方法中添加super()语句,调用父类的无参构造方法,但前提是父类必须有无参构造方法。如果父类没有无参构造方法且子类没有显式调用父类的有参构造方法,Java编译器就会报错。
相关问题
java子类调用父类构造方法,父类构造方法中的this指向的是哪个对象
在Java中,子类调用父类构造方法时,父类构造方法中的this指向的是正在被创建的父类对象。这是因为在Java中,每个对象都有一个隐式的引用this,指向当前对象。在构造方法中,this指向的就是正在被创建的对象,因此在父类构造方法中,this指向的就是正在被创建的父类对象。当子类继承父类时,子类对象会包含父类对象的所有属性和方法,因此在子类中调用父类的构造方法时,需要使用super关键字来指定要调用的父类构造方法。
父类有参数构造方法,子类无参数构造方法,用super能调用父类构造方法嘛
可以的。在子类的无参构造方法中,可以使用 `super()` 调用父类的无参构造方法。如果父类只有带参数的构造方法,子类无法继承该构造方法,但是可以在子类的构造方法中使用 `super()` 调用父类的带参数的构造方法。例如:
```java
public class ParentClass {
private int age;
public ParentClass(int age) {
this.age = age;
}
}
public class ChildClass extends ParentClass {
private String name;
public ChildClass(String name) {
super(20); // 调用父类的带参数构造方法
this.name = name;
}
}
```
在上面的例子中,子类 `ChildClass` 中没有定义任何构造方法,因此会自动继承父类的构造方法。但是父类只有一个带参数的构造方法,因此需要在子类的构造方法中使用 `super(20)` 调用父类的构造方法。这样,子类就可以通过调用父类的构造方法来初始化父类的属性。
阅读全文
相关推荐















