在 java 中,我们可以将超类 Object 传递给子类引用吗? [英] In java , can we pass superclass Object to subclass reference?

查看:19
本文介绍了在 java 中,我们可以将超类 Object 传递给子类引用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,我们可以将超类Object传递给子类引用吗?

In java, can we pass superclass Object to subclass reference ?

我知道这是一个奇怪的问题/实际上不可行,但我想了解这背后的逻辑为什么在java中不允许.

I know that it is a weird question/practically not viable, but I want to understand the logic behind this Why is it not allowed in java.

class Employee {
    public void met1(){
        System.out.println("met1");
    }
}


class SalesPerson extends Employee 
{
    @Override
    public void met1(){
    System.out.println("new met1");
    }


    public void met2(){
        System.out.println("met2");
    }

}

public class ReferenceTest {
    public static void main(String[] args) {

        SalesPerson sales = new Employee(); // line 1

        sales.met1();  // line 2

        sales.met2();  // line 3
    }
}

如果 Java 允许编译第 1 行会发生什么?问题会出现在哪里?

What would have happened if Java allowed compilation of line 1? Where would the problem arise?

欢迎任何输入/链接.

推荐答案

如果你的 SalesPerson sales = new Employee(); 语句被允许编译,这将违反 多态,这是该语言的特性之一.

If your SalesPerson sales = new Employee(); statement was allowed to compile, this would have broken the principles of Polymorphism, which is one of the features that the language has.

此外,您应该熟悉编译时类型运行时类型的含义:

Also, you should get familiar with that does compile time type and runtime type mean:

变量的编译时类型是它声明的类型,而运行时类型是变量指向的实际对象的类型.例如:

The compile-time type of a variable is the type it is declared as, while the runtime type is the type of the actual object the variable points to. For example:

Employee sales = new SalesPerson();  

sales 的编译时类型为 Employee,运行时类型为 SalesPerson.编译时类型定义了可以调用哪些方法,而运行时类型定义了实际调用期间会发生什么.

The compile-time type of sales is Employee, and the runtime type will be SalesPerson. The compile-time type defines which methods can be called, while the runtime type defines what happens during the actual call.

让我们假设这个语句是有效的:

Let's suppose for a moment that this statement was valid:

SalesPerson sales = new Employee();

正如我所说,编译时类型定义了可以调用哪些方法,因此 met2() 将有资格调用.同时,Employee 类没有 met2(),因此实际调用是不可能的.

As I said, the compile-time type defines which methods can be called, so met2() would have been eligible for calling. Meanwhile, the Employee class doesn't have a met2() and so the actual call would have been impossible.

这篇关于在 java 中,我们可以将超类 Object 传递给子类引用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆