Java 子类转父类对象
时间: 2023-09-18 12:10:30 浏览: 164
在Java中,子类对象可以被转换为父类对象。这种转换被称为向上转型或者上溯造型。它可以通过将子类对象赋值给父类引用来实现。
下面是一个示例代码:
```java
class Parent {
public void display() {
System.out.println("This is the display method of the parent class.");
}
}
class Child extends Parent {
public void display() {
System.out.println("This is the display method of the child class.");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
Parent parent = child; // 子类对象转换为父类对象
parent.display(); // 调用的是子类的方法,因为子类重写了父类的方法
}
}
```
在上面的例子中,子类`Child`对象被赋值给父类`Parent`的引用`parent`,这样就完成了子类到父类的转换。尽管调用的是父类的引用,但是由于方法的动态绑定,实际上调用的是子类中重写的方法。
需要注意的是,向上转型后,父类引用只能访问父类中定义的成员变量和成员方法,而不能访问子类中定义特有的成员变量和成员方法。如果需要访问子类特有的成员,可以使用向下转型或者进行类型判断。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)