繁体   English   中英

什么是运行时类型 object

[英]what is the runtime type object in this

  1. 我正在覆盖子 class 中的 2 种父方法,但我不知道Object ooj = new String("abc"); 正在工作中

  2. 根据我认为运行时 object 是字符串类型,但是当我将obj传递给 function 它调用Object类型的方法


PARENT CLASS
public class Parent {
    public void function(Object obj) {
        System.out.println("I'm  parent Object Type");
    }

    public void function(String str) {
        System.out.println("I'm parent String");
    }
}

CHILD CLASS

public class Chile extends Parent{
    public void function(Object oob) {
        System.out.println("I'm child object");
    }
    public void function(String str) {
        System.out.println("I'm child string");
    }

    public static void main(String[] args) {
        Parent p = new Chile();
        Object obj = new String("Gaurav");
        p.function(obj);
        String str = new String("and");
        p.function(str);

    }
}

我的问题是为什么它调用Object方法,而不是为什么不字符串

我的问题是为什么它调用 Object 方法,而不是为什么不字符串

因为编译器不再知道它是一个String

编译器决定调用哪个重载,这不是在运行时决定的。 您正在向它传递对Object的引用,因此它会查找接受Object的方法。 如果所指的事物可以是更具体的类型,它不会费心去尝试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM