next up previous
Next: Parameter passing Up: Unit 03 Previous: Example: use of static

Example: use of static methods defined in another class

Let us group now the same methods in a different class.

public class Greetings {

  public static void printGreeting() {
    System.out.println("Good morning!");
  }

  public static void printPersonalGreeting(String firstName, String lastName) {
    System.out.print("Good morning ");
    System.out.print(firstName);
    System.out.print(" ");
    System.out.print(lastName);
    System.out.println("!");
  }

  public static void printInformalGreeting (String name) {
    System.out.println("Ciao " + name + "!");
  }

  public static String personalGreeting(String firstName, String lastName) {
    return "Good morning " + firstName + " " + lastName + "!";
  }
}

Example of client:

import javax.swing.JOptionPane;

public class GreetingsClient {
  public static void main(String[] args) {
    Greetings.printGreeting();
    String fn = JOptionPane.showInputDialog("First name");
    String ln = JOptionPane.showInputDialog("Last name");
    Greetings.printPersonalGreeting(fn,ln);
    Greetings.printInformalGreeting(fn);
    JOptionPane.showMessageDialog(null, Greetings.personalGreeting(fn,ln));
    System.exit(0);
  }
}

Note that in the method main of Client we need to add in front of the calls to the static methods the name of the class where they are defined.

Note: The class Greetings can be considered a simple library that realizes different greeting functionalities. We will see later the predefined class Math, which is a library of the most commonly used mathematical functions on reals, constituted by static methods that realize the functions.


next up previous
Next: Parameter passing Up: Unit 03 Previous: Example: use of static