Accessing Fields Of Object

Publié le par ccaryjbaxtert14

I was wondering if it is possible in java to access the fields of the object from one of its own fields that is an object itself. After all, there could be several such Car instances, or none at all.


If you want the Driver to know which Car it's part of, you'll need to have a field in Driver to represent that information, and then set it by (say) passing in this from Car to the Driver constructor. Be careful though - allowing this to escape within a constructor (you call the Driver constructor from the Car constructor) can be dangerous, as you're advertising the existence of an object before it's fully initialized.


Other's have already answered your question. I would just like to point out that public data members are considered a Bad Thing(TM) in Object Oriented programming. As Francisco illustrates, you should use getters and setters instead and change the member variables themselves to private access.


With that said, I believe that your design is not the best. Why does the Driver calculate the area of the Car? Shouldn't the Car be responsible for calculating its own area, especially since it already knows its width and length? If you designed the code this way, you would completely erase the issue that causes the problem in your original question.

Pour être informé des derniers articles, inscrivez vous :

Commenter cet article