Java 中的向上转型与向下转型

类型转换简介

类型转换是 Java 中最重要的概念之一,它主要涉及隐式或显式地将一种数据类型转换为另一种数据类型。在本文中,我们将探讨对象类型转换的概念。

就像数据类型一样,对象也可以进行类型转换。然而,对于对象而言,这里只有两种类型的对象,即父对象和子对象。因此,对象的类型转换基本上意味着将一种类型的对象(即子对象或父对象)转换为另一种。类型转换主要分为两种类型:

  • 向上转型: 向上转型是指将子类对象转换为父类对象的类型转换过程。向上转型可以是隐式进行的。向上转型让我们能够灵活地访问父类的成员,但通过此特性无法访问子类的所有成员。虽然无法访问所有成员,但我们可以访问子类中特定的成员(例如被重写的方法)。
  • 向下转型: 类似地,向下转型是指将父类对象转换为子类对象的类型转换过程。向下转型不能隐式进行。

下图展示了向上转型和向下转型的概念:

!Upcasting-Vs-Downcasting

示例: 假设有一个父类。一个父类可以有许多子类。让我们以其中一个子类为例。子类继承了父类的属性。因此,子类和父类之间存在“is-a”(是一个)关系。因此,子类可以隐式地向上转型为父类。然而,父类可能不会继承子类的属性。但是,我们可以通过强制转换将父类转换为子类,这被称为向下转型。当我们显式定义这种类型转换后,编译器会在后台检查这种转换是否可行。如果不可行,编译器将抛出 ClassCastException

让我们通过下面的代码来理解这两者之间的区别:

// Java program to demonstrate
// Upcasting Vs Downcasting

// Parent class
class Parent {
    String name;

    // A method which prints the
    // signature of the parent class
    void method()
    {
        System.out.println("Method from Parent");
    }
}

// Child class
class Child extends Parent {
    int id;

    // Overriding the parent method
    // to print the signature of the
    // child class
    @Override void method()
    {
        System.out.println("Method from Child");
    }
}

// Demo class to see the difference
// between upcasting and downcasting
public class GFG {

    // Driver code
    public static void main(String[] args)
    {
        // Upcasting
        Parent p = new Child();
        p.name = "GeeksforGeeks";

        //Printing the parentclass name
        System.out.println(p.name);
        //parent class method is overridden method hence this will be executed
        p.method();

        // Trying to Downcasting Implicitly
        // Child c = new Parent(); - > compile time error

        // Downcasting Explicitly
        Child c = (Child)p;

        c.id = 1;
        System.out.println(c.name);
        System.out.println(c.id);
        c.method();
    }
}

输出

GeeksforGeeks
Method from Child
GeeksforGeeks
1
Method from Child

上述程序的说明图:

!Upcasting-Vs-Downcasting1

通过上面的示例,我们可以观察到以下几点:

  • 向上转型的语法:
Parent p = new Child();
  • 向上转型是在内部完成的,由于向上转型,该对象只能访问父类成员和子类指定成员(如被重写的方法等),而不能访问所有成员。
// This variable is not 
// accessible
p.id = 1;
  • 向下转型的语法:
Child c = (Child)p;
  • 向下转型必须在外部手动完成,通过向下转型,子类对象可以获得父类对象的属性。
c.name = p.name;
i.e., c.name = "GeeksforGeeks"
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/48787.html
点赞
0.00 平均评分 (0% 分数) - 0