public class Parent{ public int addValue(int a,int b){ return a + b; } } class Child extends Parent{ } 以下哪个方法声明能够加入到Child类中,编译正确。
时间: 2024-03-01 22:52:19 浏览: 17
以下是能够加入到Child类中并且编译正确的方法声明:
```java
public class Child extends Parent{
public int addValue(int a, int b){
return a + b + 1;
}
}
```
在Child类中重写addValue方法,需要保证方法名、参数列表和返回值类型与父类中的方法相同。在这里,Child类继承了Parent类,所以可以使用addValue方法。在Child类中重写addValue方法时,可以在方法体中调用父类的addValue方法,并进行扩展。例如,在上述代码中,Child类中的addValue方法返回a + b + 1。这样,Child类中就有了一个与Parent类中的addValue方法同名、同参数列表、同返回值类型的方法,可以正确编译。
相关问题
对于下列代码: class Parent { public int addValue( int a, int b) { int s; s = a+b; return s; } } class Child extends Parent { } 下述哪个方法可以加入类Child?
这是一道重复的问题,刚才我已经回答了,我再重复一遍:
由于Child类继承了Parent类,所以Child类可以使用Parent类的所有方法。因此,Child类可以直接使用Parent类的addValue方法。如果Child类需要覆盖(override)addValue方法,可以使用与Parent类相同的方法签名,如下所示:
```
class Child extends Parent {
public int addValue( int a, int b) {
int s;
s = a+b+1; // 增加了1
return s;
}
}
```
这样,Child类就拥有了一个addValue方法,它和Parent类的addValue方法有相同的方法签名,但是实现不同。
class Parent { public int addValue( int a, int b) { int s; s = a+b; return s; } } class Child extends Parent { } 下述哪个方法可以加入类Child? A. int addValue( int a,int b ){// do something...} B. public void addValue (int a,int b ){// do something...} C. public int addValue( int a ){// do something...} D. public int addValue( int a,int b )throws MyException {//do something...}
选项A和选项B都可以加入类Child。
由于类Child继承了类Parent,所以Child类可以访问Parent类中的public方法。因此,选项A和选项B都可以加入类Child,这两个方法都是public访问权限,且方法名称和参数列表与Parent类中的addValue方法相同,因此符合Java中的方法重写规则。
选项C的方法参数与Parent类中的addValue方法不同,因此不符合Java中的方法重写规则,不能加入类Child。
选项D的方法增加了一个throws声明,表示该方法可能会抛出一个自定义的MyException异常,这不违反Java中的方法重写规则,但是该方法参数列表与Parent类中的addValue方法相同,因此不符合Java中的方法重写规则,不能加入类Child。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)