java向上转型和向下转型
时间: 2023-06-16 13:02:36 浏览: 64
Java中的向上转型和向下转型主要用于类的继承关系中。
向上转型指的是将子类对象转换成父类对象,这样做可以提高代码的灵活性和可扩展性。例如:
```
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("Cat is eating");
}
public void meow() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Cat(); // 向上转型
animal.eat(); // 输出:Cat is eating
}
}
```
向下转型指的是将父类对象转换成子类对象,这样做需要进行类型检查和类型转换,如果类型不匹配会抛出ClassCastException异常。例如:
```
class Animal {
public void eat() {
System.out.println("Animal is eating");
}
}
class Cat extends Animal {
public void eat() {
System.out.println("Cat is eating");
}
public void meow() {
System.out.println("Cat is meowing");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Cat(); // 向上转型
if (animal instanceof Cat) { // 类型检查
Cat cat = (Cat) animal; // 向下转型
cat.meow(); // 输出:Cat is meowing
}
}
}
```
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)