Tony West wrote:I am currently taking a Java I course and ran into something involving abstract types and clone() that I don't fully understand. The attached file compiles and runs fine when compiled as a single file. However if I break it into 3 classes i.e. Shape, Square, and TestSquare, then where I try to clone a Shape reference to a Shape or Square reference (i.e. "Shape e = (Square) d.clone();") I get a compile error that "The method clone() from the type Object is not visible". I can get it to work by changing it to "Shape e = (Shape)((Square)d).clone();" but I am trying to understand why this is needed.
Tony West wrote:Thanks for the quick reply Henry! I see where you are going and understand how to make it work with the cast to Square but what confuses me is why the code above works when compiled and run as a single file? It only seems to require the extra cast when I divide it into multiple classes in the same package.
Tony West wrote:
So in summary I understand how to make it work. I just don't understand why as a single file I don't need the extra cast. Perhaps Java handles accessibility slightly different when the classes are combined in the same file?
Campbell Ritchie wrote:I always thought you were supposed to override the clone() method with public access.
What's that smell? Hey, sniff this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
|