[ASK] Several questions on Classes

Discussion in 'Spigot Plugin Development' started by Gober, Jun 2, 2018.

    1. What if I use static in a variable on another class? How to access it? What makes it different from a normal variable?
    Example:
    Code (Java):
        public static HashMap<Player, Inventory> boxes;

    2. What if I use private on a variable on another class? Could I use the get method to return it? What makes it different?
    Example:
    Code (Java):
        private Inventory box;

    3. Why I could not return a specific HashMap on another class using the get method?
    Example:
    Code (Java):
        public static HashMap<Player, Inventory> boxes;
        private Inventory box;
            public HashMap<Player, Inventory> getHashMap() {
            return this.boxes;
        }
        public static void setValue(Player b, Inventory be) {
            boxes.put(b, be);
        }
        public static void ResetValue(Player b) {
            boxes.remove(b);
        }

    // None of those above works.
     
  1. electronicboy

    IRC Staff

    Making stuff static just so that you can access it across other classes is generally a sign that you don't understand how objects work, static means that something is bound to the class itself as opposed to the instance of the class

    Your questions are entirely surrounding core object-oriented programming design, I'd heavily suggest reading up on stuff such as encapsulation, which would explain what all the fuss is about
     
    • Informative Informative x 1
  2. Static basically makes it accessible by any class, if its public though. Its better to work with non-static vars since it doesn't take up as much ram plus its better organized.

    In the example's case, you could make a simple "getter" method which you can use to return the inventory.

    Code (Java):
    public Inventory getBox(){
        return box
    }
    You can fix this by changing this

    Code (Java):
    public HashMap<Player, Inventory> getHashMap() {
            return this.boxes;
    }
    to

    Code (Java):
    public static HashMap<Player, Inventory> getHashMap() {
            return this.boxes;
    }
     
    • Winner Winner x 1