[Java] multiple class syntax

Discussion in 'Mixed Languages' started by stevemk14ebr, Feb 8, 2013.

  1. stevemk14ebr

    stevemk14ebr MDL Senior Member

    Jun 23, 2010
    267
    48
    10
    #1 stevemk14ebr, Feb 8, 2013
    Last edited by a moderator: Apr 20, 2017
    i just need to know how to properly use my own projects class methods in another class in the same project. For example:
    1) I have a project called pong
    2) in this project there are 5 classes, all need to be able to call each others methods (1 for screen management,one for keyboard input, 1 main class, etc)
    3) currently i am doing this at the top of a class file when i need to talk to another class
    Code:
    private Keyboard k;
    k=new Keyboard();
    k.getInput;
    4) that works but doesnt feel like it's the right way to do it
    5) what would be the correct way of calling another classes methods
    6) could someone explain the extends keyword:
    Code:
    oublic class steve extends Keyboard
    if you need more explaining on my confusion please ask
     
  2. Calistoga

    Calistoga MDL Senior Member

    Jul 25, 2009
    421
    199
    10
    #2 Calistoga, Feb 8, 2013
    Last edited by a moderator: Apr 20, 2017
    To avoid creating multiple instances of a class, you can create it once and pass the reference to the other classes through their constructors.
    Code:
    Keyboard kb = new Keyboard();
    SomeClass sc = new SomeClass(kb);
    OmgClass oc = new OmgClass(kb);
    
    SomeClass
    Code:
    public class SomeClass {
        private m_kb;
        
        public SomeClass(Keyboard kb) {
            m_kb = kb; /* You might want to check for null. */
        }
        
        public void doSomething() {
            m_kb.getInput();
        }
    }
    
    The m_ prefix I use means "member variable" and is just a convention. You don't have to use that.

    Alternatively, you could use static methods - methods that does not need a class instance to be called.
    Code:
    public class Yolo {
        public static void doSomething() {
            ...
        }
    }
    
    Usage
    Code:
    Yolo.doSomething();
    
    The following declaration means that the class "Steve" will inherit all the properties of the class "Keyboard".
    Code:
    public class Steve extends Keyboard
    In this case, the following would work.
    Code:
    Steve steve = new Steve();
    steve.getInput();