Linux 拨号vps windows公众号手机端

Java怎么正确的向上转型与向下转型

lewis 9年前 (2016-11-23) 阅读数 6 #程序编程
文章标签 Java

在Java中,向上转型和向下转型是用来处理父类与子类之间的关系的。

  1. 向上转型:将一个子类的对象转换为父类的对象。这样可以实现父类引用指向子类对象,实现多态。向上转型是自动进行的,无需强制转换。
class Animal {
   public void eat() {
      System.out.println("Animal is eating");
   }
}
class Dog extends Animal {
   public void eat() {
      System.out.println("Dog is eating");
   }
}

public class Main {
   public static void main(String[] args) {
      Animal animal = new Dog(); // 向上转型
      animal.eat(); // 输出 Dog is eating
   }
}
  1. 向下转型:将一个父类的对象转换为子类的对象。需要使用强制类型转换操作符,并且需要进行类型检查以避免ClassCastException异常。
class Animal {
   public void eat() {
      System.out.println("Animal is eating");
   }
}
class Dog extends Animal {
   public void eat() {
      System.out.println("Dog is eating");
   }
   public void bark() {
      System.out.println("Dog is barking");
   }
}

public class Main {
   public static void main(String[] args) {
      Animal animal = new Dog(); // 向上转型
      if (animal instanceof Dog) {
         Dog dog = (Dog) animal; // 向下转型
         dog.bark(); // 输出 Dog is barking
      }
   }
}

需要注意的是,向下转型时一定要进行类型检查,以避免出现ClassCastException异常。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门