Skip to main content
gamedev.net
🔒 Locked

Object Oriented Programming question

Started by Swattkidd 2 replies 800+ views
Original Post
Swattkidd
Swattkidd
Ok, well i am having a bit of difficulty with an OOP concept. I am using Java but the question is just in general pretty much ( i think). lets say i have a constructor that requires you to input a Wallet.(Wallet being its own class) public Person(Wallet w){ } and then the Wallet constructor requires you to input a Person. public Wallet(Person p){ } how could you create a person? i cant do this

Wallet wallet;
Person c;
c = new Person(wallet);
wallet = new Wallet(c);

i get the "may not be initialized error".
Morrandir
Morrandir
Well, OOP principles aren't designed to support cases which do not make too much sense. I can't think of a context (off the top of my head) in which this relationship would be valid.

If your goal was to have a Person with a Wallet, and in turn make the Wallet know which Person holds it, then have a setOwner method for the Wallet which stores a reference for a Person in the Wallet object and call this method in the Person constructor.

Cheers
SamLowry
SamLowry
Bidirectional associations (Person links to Wallet, and vice versa) certainly do make sense. The only way to achieve this easily in Java is to use state:
Person p = new Person(); // Wallet-less personWallet w = new Wallet(p); // !! Invalid in-between statep.setWaller(w); // Everything ok again// OrWallet w = new Wallet(); // Ownerless walletPerson p = new Person(w); // Invalid statew.setOwner(p);


You might want to encapsulate this in a separate static methode:
class Person{    public static Person Create()    {       Person p = new Person();       Wallet w = new Wallet(p);       p.setWallet(w);       return p;    }    private Person() { ... }    private void setWallet() { ... }}

This way you can ensure that the association will always be valid (at creation time at least, changing the association during the object's lifetime should also be completly handled internally by the objects IMO).
Zahlman
Zahlman
Does a Person ever need to grab an existing Wallet? I should think not, because the Wallet must already belong to some other Person (the one specified when constructing the Wallet) and stealing it away would be kinda bad. :)

Therefore, since we need to construct a new Wallet for each Person, the simple and obvious solution is to do it in the Person constructor:

class Person {  private Wallet w;  public Person() { w = new Wallet(this); }}class Wallet {  private Person p;  public Wallet(Person owner) { p = owner; }}Person swattkidd = new Person();// now you have your own Wallet, named swattkidd.w (of course, it's private...).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.