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(" ");

  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) {
    String fn = JOptionPane.showInputDialog("First name");
    String ln = JOptionPane.showInputDialog("Last name");
    JOptionPane.showMessageDialog(null, Greetings.personalGreeting(fn,ln));

Note that in the method main() of GreetingsClient 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