๐ŸŽ“ A1Learner
๐Ÿ”
0 of 48 lessons completed

Java Class Methods

Methods declared inside a class carry the work of the class. A static method is called on the class, and a plain method is called on an object.

A static method called on the class

The info method carries the static keyword. The call uses the class name Dog, and no object exists in the program.

class Dog {
  static void info() {
    System.out.println("Dogs bark");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog.info();
  }
}

A plain method called on an object

The bark method has no static keyword. The program builds a Dog object first, and the call runs through that object.

class Dog {
  void bark() {
    System.out.println("Woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.bark();
  }
}

A plain method called on the class fails

This call uses the class name for a plain method. The compiler refuses the call because bark needs an object.

class Dog {
  void bark() {
    System.out.println("Woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog.bark();
  }
}

Example

class Dog {
  static void info() {
    System.out.println("A dog is an animal");
  }

  void bark() {
    System.out.println("Woof");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog.info();
    Dog dog = new Dog();
    dog.bark();
  }
}

Key points

  • The static keyword marks a method that belongs to the class.
  • A static method is called with the class name and a dot.
  • A plain method has no static keyword.
  • A plain method is called on an object.
  • A plain method called on the class name is refused by the compiler.
  • One class can hold both static and plain methods.

In this example, the Dog class holds one static method and one plain method. The static call runs through the class name and prints the first line. The plain call runs through the dog object and prints Woof.

Note

main is static, so code in main follows the same rule for plain methods.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How is a static method of the Dog class called?