Search code examples
javaandroidclassextend

Java extends vs object reference?


I'm working on a android app, and I have a user class that has properties about the user. I also have a class that has views (i.e. TextViews) that shows the appropriate property on the screen, these are for GUI purposes. This GUI class needs the properties of the user class so I can access those too. So I am left with a decision to make that I am not sure. I want to pick the one that's better in programming practices. I don't want to merge all the properties including the GUI together in one class.

The way I see it is, I could either have the GUI class extend the user class or have the GUI class have a private global variable which holds the user object.

Does anyone know which is better and why?


Solution

  • Using encapsulation is better. It makes no sense for a GUI class to extend a 'user' class -- the two don't possess any sort of "is-a" relationship. It does make sense, however, for the GUI class to maintain a user object to work with.

    In other words, it doesn't make sense to say a GUI object is a user object, but it does make sense to say a GUI object contains user a user object.

    Lastly, you generally want to keep your front-end and back-end as separate and modular as possible. Having your GUI class extend your user class undermines this principle.