I’m studying Prototype Design pattern I can’t understand the syntax below. Can you explain it to me? What does it mean for a class to be put in parentheses and initialized like this :
Person person2 = (Person) person1.doSomthing();
Code in context:
// code in int main
Person person1 = new Person("Fred");// this is understood
System.out.println("person 1:" + person1);// this is understood
Person person2 = (Person) person1.doClone();//not understood
System.out.println("person 2:" + person2);// this is understood
Is this syntax in java for casting?
It is a cast. In other words, the
doSomething()method is most likely not declared to return aPerson. So you need to first cast the returned value to aPersonbefore assigning it toperson2.If
doSomethingdoes return aPerson, then the cast is not necessary.And if the actual type of the object returned by
doSomethingis not assignable to a Person, the cast will throw aClassCastExceptionat runtime.More info about it in the JLS #15.16: