Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

How do I make sense of this Java syntax, a class name in parentheses before a method name?

I'm seeing this syntax and can't understand what it means. It doesn't look like a regular object instantiation. The 'new' keyword isn't there and the class name is put in parenthesis... then there's a method call at the end.

MyClass myObj = (MyClass) someMethod(arg);

question from:https://stackoverflow.com/questions/65926932/how-do-i-make-sense-of-this-java-syntax-a-class-name-in-parentheses-before-a-me

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In Java,

someMethod(arg)

is a call of a method named someMethod with a single parameter arg.

All methods (except void ones) return a value. The type of the return value is part of method definition. In your case, we don't know what the someMethod returns (because you didn't provide its definition), but we can assume it is not void.

The expression

(MyClass) obj

is a type cast, which tells the compiler to treat obj as if it was of type MyClass. During compilation, compiler checks that the definition of obj is compatible with MyClass, and if it is, it allows you to treat it like one. During run time, Java virtual machine checks that the actual object obj is actually instance of class MyClass. If it is not, it will throw a ClassCastException.

Typically, type casts are used to "upgrade" how the compiler sees an object into something more specific. For example, if a pet shop by definition sells Animals, and you ordered a Hamster, then you can reasonably assume thet what you get is not just an Animal, but a Hamster (assuming Hamster extends Animal).

Now, put this together and you get a type cast applied to a method return value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...