Getting a method from another class

Discussion in 'Spigot Plugin Development' started by CapitanoKidd, May 26, 2016.

Thread Status:
Not open for further replies.
  1. Can anyone explain me why if I call a method in the same class my code works, but if I create a method in another class it won't work?

    Here an example with my code:

    In the same class, called Token.java
    Code (Text):

        private static Main plugin;
        public Token(Main pl) {
            plugin = pl;
        }

    /*
    some code
    */


    if(Integer.parseInt(args[2])>0){
                                try {
                                    balance = this.getBalance(p.getName());
                                } catch (SQLException e1) {
                                    e1.printStackTrace();
                                }
                                if(balance > Integer.parseInt(args[2])){
                                    try {
                                        this.removeTokens(p.getName(), Integer.parseInt(args[2]));
                                        p.sendMessage(ChatColor.GREEN + "Sent " + ChatColor.GRAY + args[2] + " Tokens to " + ChatColor.GRAY + args[1]);
                                        this.addTokens(args[1],Integer.parseInt(args[2]));
                                        Player p2 = plugin.getServer().getPlayer(args[1]);
                                        p2.sendMessage(ChatColor.GRAY + args[2] + ChatColor.GREEN + " Tokens has been sent by " + ChatColor.GRAY + p.getName());
                                    } catch (NumberFormatException e) {
                                        p.sendMessage(ChatColor.RED + "Usage: /token pay <player> <tokens>");
                                    } catch (SQLException e) {
                                        p.sendMessage(ChatColor.RED + "An error occurred. Contact an Admin to fix this.");
                                    }
                                }
                                else{
                                    p.sendMessage(ChatColor.RED + "You do not have enough Tokens.");
                                    return false;
                                }
                            }
     
    And this is my method (it is in the same class, Token.java)
    PLEASE DO NOT COMMENT THE "USELESS" CODE, I KNOW THAT I HAVE TO RE-WRITE IT.
    Code (Text):
        public int getBalance(String username) throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
            ps = conn.prepareStatement("SELECT balance FROM PlayersData WHERE username = ?");
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                balance = rs.getInt("balance");
            }
            rs.close();
            return balance;
        }
        public void addTokens(String username, int tokens)throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
            balance = this.getBalance(username);
            balance = balance + tokens;
            ps = conn.prepareStatement("UPDATE PlayersData SET balance = ? WHERE username = ?");
            ps.setInt(1, balance);
            ps.setString(2, username);
            ps.executeUpdate();
        }
        public void removeTokens(String username, int tokens)throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
                balance = this.getBalance(username);
                balance = balance - tokens;
                ps = conn.prepareStatement("UPDATE PlayersData SET balance = ? WHERE username = ?");
                ps.setInt(1, balance);
                ps.setString(2, username);
                ps.executeUpdate();
        }
     


    This code will work... but if I create another class called TokenHandler.java in another package called Handlers and I write the addTokens, getBalance and removeTokens in this class, the first code won't work.

    Example:
    TokenHandler.java
    Code (Text):
       
    //plugin is the instance of Main class
    //but I'm not sure on HOW to instantiate it in this class...
     public int getBalance(String username) throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
            ps = conn.prepareStatement("SELECT balance FROM PlayersData WHERE username = ?");
            ps.setString(1, username);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                balance = rs.getInt("balance");
            }
            rs.close();
            return balance;
        }
        public void addTokens(String username, int tokens)throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
            balance = this.getBalance(username);
            balance = balance + tokens;
            ps = conn.prepareStatement("UPDATE PlayersData SET balance = ? WHERE username = ?");
            ps.setInt(1, balance);
            ps.setString(2, username);
            ps.executeUpdate();
        }
        public void removeTokens(String username, int tokens)throws SQLException{
            if(conn==null){
                conn = plugin.connect();
            }
                balance = this.getBalance(username);
                balance = balance - tokens;
                ps = conn.prepareStatement("UPDATE PlayersData SET balance = ? WHERE username = ?");
                ps.setInt(1, balance);
                ps.setString(2, username);
                ps.executeUpdate();
        }
     
    And this is my Token.java class
    Code (Text):

        private static Main plugin;
        private static TokenHandler instance = new TokenHandler();
        public Token(Main pl) {
            plugin = pl;
        }

    /*
    some code
    */


    if(Integer.parseInt(args[2])>0){
                                try {
                                    balance = instance.getBalance(p.getName());
                                } catch (SQLException e1) {
                                    e1.printStackTrace();
                                }
                                if(balance > Integer.parseInt(args[2])){
                                    try {
                                        instance.removeTokens(p.getName(), Integer.parseInt(args[2]));
                                        p.sendMessage(ChatColor.GREEN + "Sent " + ChatColor.GRAY + args[2] + " Tokens to " + ChatColor.GRAY + args[1]);
                                        instance.addTokens(args[1],Integer.parseInt(args[2]));
                                        Player p2 = plugin.getServer().getPlayer(args[1]);
                                        p2.sendMessage(ChatColor.GRAY + args[2] + ChatColor.GREEN + " Tokens has been sent by " + ChatColor.GRAY + p.getName());
                                    } catch (NumberFormatException e) {
                                        p.sendMessage(ChatColor.RED + "Usage: /token pay <player> <tokens>");
                                    } catch (SQLException e) {
                                        p.sendMessage(ChatColor.RED + "An error occurred. Contact an Admin to fix this.");
                                    }
                                }
                                else{
                                    p.sendMessage(ChatColor.RED + "You do not have enough Tokens.");
                                    return false;
                                }
                            }
     
     
  2. Pass an instance or use static?
     
    • Agree Agree x 1
  3. What you have to do it use getters, setters and constructors.
    For example:

    In your main class define all your plugins e.g.
    private MainClass plugin;
    private MethodClass methods;

    then set the instance of your main claass variable in on enable with
    plugin = this;

    then you can do the same with the other variables e.g.
    methods = new Methods(this);

    then you would create a getter in your main class still outside everything else e.g.
    public MethodClass getMethods(){
    return methods;
    }

    Then you would create a constructor in your methods class e.g.
    private final MainClass plugin;
    public MethodClass(MainClass plugin){
    this.plugin = plugin;
    }

    Then from any class you can use e.g.
    plugin.getMethods().methodName;

    ps refrain from using static instances because i quote from a friend
    "Java is an Object-Oriented-Programming language (OOP) and typically when someone has all of their code filled with static methods, one can assume he/she is a lazy developer that doesn't really know what he/she is doing."
     
    • Like Like x 1
    • Agree Agree x 1
    • Useful Useful x 1
  4. hmmm someone told me that there's an error if you did

    Code (Java):
    public int i() {
    return 0;
    }
    you have to put some space
    Code (Java):
    public int i () {
    return 0;
    }
    correct me if I'm mistaken
     
    • Optimistic Optimistic x 2
  5. Java doesn't care about spacing
     
  6. well so that's a noob information sorry about.
     
  7. Java is entirely OOP, which is very annoying if you are (i assume?) coming from non-OOP languages like C, or simpler C++

    Every file in java represents at least one object, there is no such thing as code that is not a class object, everything has to be instantiated, including your main class (bukkit does this for you).
     
  8. Correct me if I'm wrong but C++ is (in a way) object oriented as it's considered a "multi-paradigm" language.
     
  9. You are completely correct. It gives the option of writing procedural or OOP code, or combining the two. Honestly a combination of the two is much more efficient and easy to use than being forced entirely into OOP (it overcomplicates, not everything needs a class).
     
    • Like Like x 1

  10. Thank you, that worked! :D
     
    • Like Like x 1
Thread Status:
Not open for further replies.