Is there a way to hide a method in java based on constructor? -
suppose have class person. person can have age or car. make method getcar() available user if user used constructor person(int age, boolean hascar). if created person object person(int age) method getcar shouldn't accessible. there way that? i.e. hide getcar() method. without using inheritance.
no, , that's good thing.
the code might call person.car() not know at compile time how person constructed at runtime. person may have been created code compiled separately source file, package, or library entirely.
what can person.getcar(), when person not have car, 1 of following:
- return null
- return magic value
- or throw exception (preferably hascar() method, allow normal execution avoid throwing exception).
alternatively, if allow inheritance, have both person class , personwithcar class, , use instanceof distinguish between them. however, if follow approach more few has-a attributes, explodes many classes.
Comments
Post a Comment