Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Producing a read-only copy of a class, howto

Tags:

java

casting

Given the following UML representation, how can i get an instance of a BullDog , that only has getter methods exposed?

  • Instance of the BullDog should not have any of the setter methods available.
  • Instance of the BullDog should only have getter methods (3 of them) available

Basically the question is .. what do i cast new BullDog to?

enter image description here

like image 267
James Raitsev Avatar asked Sep 21 '11 22:09

James Raitsev


2 Answers

Since HealthyPet and Pet are unrelated there's nothing you can cast to that will give you all 3 getter methods(getMetabolism(),getName() and getAge()). Now if HealthyPet extended Pet (and I'm really not sure why it doesn't) you'd be in business. Because then you could cast to HealthyPet, return that interface, and a caller would only see the 3 getter methods (of course I'm talking without fancy introspection which should allow them to discover everything).

like image 63
Simeon G Avatar answered Oct 10 '22 05:10

Simeon G


You need HealthyPet to extend Pet. Then you cast your BullDog instance to HealthyPet.

like image 35
Michael M. Avatar answered Oct 10 '22 05:10

Michael M.