java 重写_Java的重写
时间: 2024-03-07 12:53:17 浏览: 31
Java中的重写是指子类重新定义父类中已有的方法,使得子类可以根据自己的需要对该方法进行实现。重写的方法必须具有与父类中被重写的方法相同的名称、参数列表和返回类型。在重写的方法中,可以使用super关键字调用父类中被重写的方法。重写方法的访问修饰符不能比父类中被重写的方法的访问修饰符更严格。例如,如果父类中被重写的方法是public的,那么重写的方法不能是private的。重写方法还必须抛出与父类中被重写的方法相同的异常或者其子类异常,或者不抛出异常。
相关问题
java重写
Java中的重写指的是子类重新实现了父类中已有的方法,方法名、参数列表和返回值类型必须与父类中的方法完全一致。重写的目的是为了实现多态性,让子类对象可以在运行时动态地调用其父类中已有的方法。
在重写方法时,需要注意以下几点:
1. 访问修饰符不能缩小:重写的方法不能将父类方法的访问修饰符缩小,即不能由public变成protected或private。
2. 返回类型要一致:重写的方法返回类型必须与父类方法的返回类型一致,或者是其子类。
3. 参数列表必须一致:重写的方法的参数列表必须与父类方法的参数列表一致。
4. 抛出的异常不能更多:重写的方法抛出的异常不能比父类方法抛出的异常更多,可以比父类方法抛出更少或者不抛出异常。
下面是一个重写的示例代码:
```java
class Animal {
public void move() {
System.out.println("Animal can move");
}
}
class Dog extends Animal {
@Override
public void move() {
System.out.println("Dog can run and walk");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Animal();
Animal b = new Dog();
a.move(); // 输出 "Animal can move"
b.move(); // 输出 "Dog can run and walk"
}
}
```
在上面的代码中,Animal类中有一个move方法,它被子类Dog重写了。在main方法中,通过Animal类创建了一个Animal对象a和一个Dog对象b,分别调用它们的move方法,输出了不同的结果。
Java重写
Java中的重写(Override)指的是子类重新定义父类的方法。子类可以在继承父类的方法后,通过重写的方式来改变方法的实现细节,以满足自己的需求。
要进行方法重写,必须满足以下条件:
1. 父类中该方法必须是非私有、非静态、非 final 的实例方法。
2. 子类中的方法必须和父类中被重写的方法具有相同的方法名称、参数列表和返回类型。
3. 子类中的方法不能缩小父类方法的访问权限,即不能将父类方法的访问权限从 public 缩小为 protected 或 private。
4. 子类中的方法不能抛出比父类方法更多或更宽泛的异常。
示例如下:
```
class Animal {
public void move() {
System.out.println("动物在移动");
}
}
class Dog extends Animal {
public void move() {
System.out.println("狗在跑");
}
}
public class Test {
public static void main(String[] args) {
Animal animal = new Animal();
animal.move();
Dog dog = new Dog();
dog.move();
}
}
```
输出结果:
```
动物在移动
狗在跑
```
在上面的例子中,Animal类中有一个move()方法,Dog类继承了Animal类并重写了move()方法。在主方法中创建了一个Animal对象和一个Dog对象,分别调用它们的move()方法,可以看到Animal对象的move()方法输出"动物在移动",而Dog对象的move()方法输出"狗在跑",证明了重写的实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)