2

I would like to know if somebody knows exactly what happens when the line of code comes to play:

class Class{}

class Math extends Class{}

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

{

   new Math();  //Line 8
   (Class)new Math();//     Line 9

}

I thoroughly understand that the "new keyword" serves as object instance creator in the heap memory. However in the preceding bit of code you can see that line 9 makes an unusual use of this keyword (new). Line 8 it's ok and compiles fine. but line 9 requires to assign the content to some other references. Thus this implies that each time the cast operand is present, in this case (Class)new Math, a new reference(underscoring reference and not object) is going to be instantiated.

Does it work in this way? If not, could you explain to me why it compiles fine in line #8 and it gives an error in line #9? (obviously due to the casting function not to be put there but why not?)

4

4 回答 4

6

Since you don't have referencing variable on line 9 compiler doesn't consider this statement to be valid.

Cast is required when you have a referencing variable of a 'more specific' type that the object itself. For example, when you're performing an upcast you don't need it:

Class obj = new Math();

And you need an explicit cast when you're performing downcast:

Class obj = new Math();
Math math = (Math) obj;
于 2013-01-30T15:40:51.790 回答
3

(Class)new Math() does two things:

  1. create a new instance of Math
  2. cast the created Math instance to Class.

Since Math extends Class, every Math instance is a Class instance, and you don't need any cast to assign a Math instance to a variable of type Class. The cast is thus completely useless. And since you don't assign the created Math instance to any variable, the cast is even more useless.

于 2013-01-30T15:41:28.110 回答
1

Both lines build a Math instance. Since in this case, Math is a subclass of Class (which is kinda unusual, but okay, I'm playing along).

So line 9, (Class)new Math(); tells the JVM to forget about the fact it's a specialized instance of Class and just treat it like a generic Class object. That basically means that if you did:

Class c = (Class)new Math(); and Math had methods not inherited from Class, you wouldn't be able to call them on object c.

Note however that c is still actually an instance of Math.

I'm not sure really what the point is in this example, but typically you do this if you want your code work off of the generic definition of an object and not worry about specific implementations. I don't know, the whole example seems goofy to me.

于 2013-01-30T15:44:25.013 回答
0

In this particular case it's simply because no assignment is made to a variable on line 9.

于 2013-01-30T15:55:36.260 回答