What's Better?

Discussion in 'Plugin Development' started by chasechocolate, Feb 2, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    chasechocolate

    Hi, I was wondering what the best way to get an instance of a class is. Would I create a static instance of the class in the class like this:
    Code:java
    1. public <classname> instance;
    2. public static <classname> getInstance(){
    3. return instance;
    4. }

    Or would I create a constructor in another class:
    Code:java
    1. private <otherclass> class;
    2. public <classname>(<otherclass> class){
    3. this.class = class;
    4. }

    I've seen it both ways, but I was wondering which would be the easiest to use. Thanks!
     
  2. Offline

    raGan.

    How would you get instance in second option ?

    Edit: nvm, I was confused by the name of the variable. I see no point in creating second class when you can have static getInstance() method.
     
  3. Offline

    Tirelessly

    You can't use "this" in a static method, as the static method isn't related to an object.
     
  4. Offline

    raGan.

    He's right, you will have to have private static field in your class and a way to set it.
    Code:
    private static YourClass instance;
    You can then have public static getter and protected setter, to prevent people from rewriting your istance.
     
  5. Offline

    chasechocolate

    Yeah, I know, just had no IDE when I wrote it.
     
Thread Status:
Not open for further replies.

Share This Page