简体   繁体   中英

Understanding “new” keyword in java

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?)

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;

(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.

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.

在这种特殊情况下,这只是因为没有对第9行的变量进行赋值。

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