Java Application/Class Design - How do accessors in Java work?

How do I write the getDB() function and use it properly?

Here is a code snippet of my App Object:

public class MyApp extends UiApplication {

    private static PersistentObject m_oStore;
    private static MyBigObjectOfStorage m_oDB;

    static {
        store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
    }

    public static void main(String[] args) {
        MyApp theApp = new MyApp();
        theApp.enterEventDispatcher();
    }
    public MyApp() {
        pushScreen(new MyMainScreen());
    }

    // Is this correct?  Will it return a copy of m_oDB or a reference of m_oDB?
    public MyBigObjectOfStorage getDB() {
        return m_oDB;  // returns a reference
    }

}


Asked by: Rebecca312 | Posted: 23-01-2022






Answer 1

public MyBigObjectOfStorage getDB() {
  return m_oDB;
}

As you put it is correct. It will return a copy of the reference, which is kind of in between a copy and a reference.

The actual object instance returned by getDB() is the same object referenced by m_oDB. However, you can't change the reference returned by getDB() to point at a different object and have it actually cause the local private m_oDB to point at the new object. m_oDB will still point at the object it was already.

See http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html for more detail.

Although looking through your code there, you never set m_oDB at all, so getDB() will always return null.

Answered by: Hailey806 | Posted: 24-02-2022



Answer 2

public MyBigObjectOfStorage getDB() {
    Object o = store.getContents();
    if ( o instanceof MyBigObjectOfStorage ) {
        return (MyBigObjectOfStorage) o;
    } else {
        return null;
    }
}

Answered by: Lenny723 | Posted: 24-02-2022



Answer 3

I am one of those folks that are very much against using singletons and/or statics as it tends to make unit testing impossible. As this is posted under best practices, I suggest that you take a look at using a dependency injection framework. Personally I am using and prefer Google Guice.

Answered by: Kate226 | Posted: 24-02-2022



Similar questions





Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top