Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - Parentheses around data type?

I am a beginning programmer and came across this in my textbook:

public boolean equals(DataElement otherElement)
{
    IntElement temp = (IntElement) otherElement;            
    return (num == temp.num);
}

IntElement is a subclass of DataElement. num is an int storing a value for a linked list.

What is the purpose of (IntElement) after temp =? What would be wrong with IntElement temp = otherElement? And, in general, what does putting a data type in parentheses like that do?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This is called casting, see here:

Basically, by doing this:

IntElement temp = (IntElement) otherElement;  

you are telling compiler to ignore the fact you declared otherElement as DataElement and trust you it is going to be an IntElement and not DataElement or some other subclass of DataElement.

You cannot do just IntElement temp = otherElement; as this way you would make otherElement, which was defined as DataElement become some other element, in this case IntElement. This will be a big blow to type-safety, which is the reason types are defined at the first place.

This could technically be done using type inference:

however Java does not support that and you have to be explicit.

If it's possible to get other elements, you may want to use instanceof to check the type runtime before casting:

  • Operators/TheinstanceofKeyword.htm">http://www.java2s.com/Tutorial/Java/0060_Operators/TheinstanceofKeyword.htm

At some point after you go through this, you might want to take a look at generics, too:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...