调用超类(父类)构造函数的方式取决于你使用的编程语言。下面以最常见的几种语言为例说明。
super()(推荐)class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # 调用父类构造函数
self.age = age
✅ 优点:
class Child(Parent):
def __init__(self, name, age):
Parent.__init__(self, name)
self.age = age
⚠️ 缺点:
selfsuperclass Parent {
Parent(String name) {
this.name = name;
}
}
class Child extends Parent {
Child(String name, int age) {
super(name); // 必须是第一行
this.age = age;
}
}
✅ 说明:
super(...) 必须放在子类构造函数第一行super() 可省略(编译器自动加)class Parent {
public:
Parent(string name) {
this->name = name;
}
};
class Child : public Parent {
public:
Child(string name, int age) : Parent(name) { // 初始化列表
this->age = age;
}
};
✅ 特点:
class Parent {
constructor(name) {
this.name = name;
}
}
class Child extends Parent {
constructor(name, age) {
super(name); // 必须先调用 super
this.age = age;
}
}
⚠️ 注意:
super() 才能使用 this| 语言 | 调用方式 | 是否必须第一行 |
|---|---|---|
| Python | super().__init__() |
否 |
| Java | super(...) |
✅ 是 |
| C++ | 初始化列表 | ✅ 是 |
| JS | super(...) |
✅ 是 |
如果你有具体语言或场景(如多继承、接口、抽象类等),可以告诉我,我可以给你更具体的示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。