user336242
user336242

Reputation:

What does this Java construct mean - OneClass object = ( OneClass ) anotherObject;

Sorry for the horrendous question, don't know how else to describe it,

I'm naturally a PHPer and i'm currently looking over some java and come across this section. The first line is just there for context, it is the line starting with QuotaKey that I'm interested in.

Key key = Keys.getKeyInstance( Keys.getKeyClass( cond.getKey( ) ) );  
QuotaKey quotaKey = ( QuotaKey ) key;

Upvotes: 0

Views: 149

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

Assuming that QuotaKey is a subclass of Key, you are looking at a cast operator that converts a variable of the type Key to a variable of type QuotaKey. You can write the same fragment more succinctly without a temporary variable:

QuotaKey quotaKey = (QuotaKey)Keys.getKeyInstance(Keys.getKeyClass(cond.getKey()));

This operation checks for the key to be of the correct type before coercing its type to subclass, and cause ClassCastException on failures. It is a good idea to minimize the number of such casts in your program, because their validity cannot be reliably checked at compile time.

Upvotes: 1

What you're looking at is called type casting (in this particular case downcasting), it is just to use a variable of type QuotaKey with the reference of type Key which I assume is a superclass or superinterface of QuotaKey.

Upvotes: 0

user12345613
user12345613

Reputation: 833

It's a cast. It coerces the type of key into a QuotaKey.

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160181

It's a cast, turning a Key into a QuotaKey.

JLS 15.16, Cast Expressions

http://www.javabeginner.com/learn-java/java-object-typecasting

Upvotes: 2

Related Questions