[Java] About calling instance methods

less than 1 minute read

A memo about the format of instance method calls.

Method call format

  • [Method name (argument)] for methods defined in the same instance
  • [Variable.Method name (argument)] for the method defined in the instance
  • [class name.method name (argument)] for static method

Method defined in the same instance

Test.java


public class Test {
  public void SayHello() {
    System.out.println("Hello World");
  }
  public void Display() {
    SayHello();
  }
}

Methods defined in different instances

Create a new instance and use the reference that contains the variable (hello.SayHello();).

Hello.java


public class Hello{
  public void SayHello() {
    System.out.println("Hello World");
  }
}

Test.java


public class Test {
  public static void main(final String[] args) {
    Hello hello = new Hello();
    hello.SayHello();
  }
}

static method

Use a class name reference (Hello.SayHello();).

Hello.java


public class Hello{
  public static void SayHello() {
    System.out.println("Hello World");
  }
}

Test.java


public class Test {
  public static void main(final String[] args) {
    Hello.SayHello();
  }
}

bonus

No parentheses after it are access to the instance fields.

References

Thorough capture Java SE11 Silver problem collection

Tags:

Updated: