super使用的代码示例
时间: 2024-05-07 13:17:16 浏览: 14
好的!以下是一个常见的super使用代码示例:
```
class Parent:
def __init__(self):
self.num = 0
def add_num(self, val):
self.num += val
class Child(Parent):
def __init__(self):
super().__init__()
self.double_num = 0
def add_num(self, val):
super().add_num(val)
self.double_num += val * 2
```
在这个例子中,我们有一个父类Parent和一个子类Child。子类Child继承了父类Parent。子类Child覆盖了父类Parent的add_num()方法,并调用了父类的add_num()方法使用super(),然后添加自己的double_num实例变量。这个例子演示了如何使用super()调用父类方法,并在子类中添加额外的功能。
相关问题
Java中使用super的代码示例
好的,以下是Java中使用super的代码示例:
```
public class ParentClass {
protected int number;
public ParentClass(int number) {
this.number = number;
}
public void print() {
System.out.println("ParentClass number = " + number);
}
}
public class ChildClass extends ParentClass {
private String name;
public ChildClass(int number, String name) {
super(number);
this.name = name;
}
@Override
public void print() {
super.print();
System.out.println("ChildClass name = " + name);
}
}
```
在这个示例中,ChildClass是ParentClass的子类。在ChildClass的构造方法中使用了super关键字来调用父类的构造方法,并将传递给ChildClass的参数传递给了父类。在ChildClass的print方法中,使用了super关键字来调用父类的print方法,然后再输出ChildClass自己的属性。
startActivityForResult具体使用代码示例
当您使用 startActivityForResult() 方法启动一个 Activity 时,您可以在启动的 Activity 中获取结果并将其传递回调用 Activity。以下是一个使用 startActivityForResult() 方法的示例代码:
// 在调用 Activity 中启动另一个 Activity
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, REQUEST_CODE);
// 在启动的 Activity 中设置结果并返回
Intent resultIntent = new Intent();
resultIntent.putExtra("result", "这是返回的结果");
setResult(Activity.RESULT_OK, resultIntent);
finish();
// 在调用 Activity 中获取结果
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
String result = data.getStringExtra("result");
// 处理返回的结果
}
}
请注意,这只是一个示例代码,您需要根据您的实际需求进行修改。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)