简体   繁体   中英

Why do I have to use the Object class as a reference type to make this program work?

The following class is the correct way. The code with 4 stars around it is what is going to change in the next (incorrect) class.

public class Hello
{
    public void go()
    {
        Hello aDog = new Hello();
        **Object** sameDog = getObject(aDog);
        System.out.println(aDog);
        System.out.println(sameDog);
    }

    public Object getObject(Object o)
    {
        return o;
    }
}

This is the next class

public class Hello
{
    public void go()
    {
        Hello aDog = new Hello();
        **Hello** sameDog = getObject(aDog);
        System.out.println(aDog);
        System.out.println(sameDog);
    }

    public Object getObject(Object o)
    {
        return o;
    }
}

And finally, I have my tester class.

public class HelloTester {
    public static void main(String[] args) {
        Hello a = new Hello();
        a.go();
    }
}

The following output is from the correct class:

Hello@2a139a55
Hello@2a139a55

The incorrect code does not work (obviously).

Why is this?

The function getObject() returns an "Object" type object. When pointing to an Object type with a Hello type pointer,you are doing implicit up casting, which is not allowed

getObject returns an Object whereas you assigned it to a Hello type. You should "cast" it to an Hello object:

        **Hello** sameDog = (Hello) getObject(aDog);

The method getObject is explicitly declared to return java.lang.Object - that's why it the compiler will not allow you to assign its result to a variable of a more explicit type, which is in this case Dog . There is nothing declaring that the return type of this method will be of the same type like the parameter - it could be any Object can be passed and therefore the return type is Object .

If you rewrite your code to use generics, you can be sure to get a Dog instance at compile time:

public <T> T getObject(T object)
{
    return object;
}

This declaration consists of multiple parts:

  • public - the method is public.

  • <T> all parameters of this method are declared here. In this case this is a unconstrained (eg no upper or lower bounds like T extends List ) single parameter - T .

  • T - the return type of this method will be the generic type T .

  • getObject - the method name.

  • T object - a parameter of type T named object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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