Parentheses around data type?

前端 未结 5 988
醉梦人生
醉梦人生 2020-12-03 12:22

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

public boolean equals(DataElement otherElement)
{
    IntElement temp = (IntElement) otherEl         


        
相关标签:
5条回答
  • 2020-12-03 12:59

    This is called casting, see here:

    • http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

    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:

    • http://en.wikipedia.org/wiki/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:

    • http://en.wikipedia.org/wiki/Generics_in_Java
    0 讨论(0)
  • 2020-12-03 13:03

    The purpose of (IntElement) after temp is performing a type conversion, more technically, a cast, where you're saying that otherElement, which is a parameter of type DataElement, should be taken as an object of the more concrete type IntElement.

    0 讨论(0)
  • 2020-12-03 13:04

    (IntElement) casts otherElement which is of type DataElement to type IntElement

    Check out this link about Java Types and Type Conversion (Casting) for a more thorough description.

    0 讨论(0)
  • 2020-12-03 13:07

    jmein is correct, it tells the compiler/interpreter to turn the one variable type into another. In reality it is just telling the processor to treat it as another type. In C this is a blessing and a curse, in java, what looks like you are writing, you MUST cast the variable to treat it differently.

    0 讨论(0)
  • 2020-12-03 13:07

    It is a type castSee the example here

    0 讨论(0)
提交回复
热议问题