Academic Java    Java Tutorial  >  Classes  >  class method

class method Example

Java class method EXAMPLE output This definition of the Book class has a class method getNumBooks().

A class method, identified by the keyword static, operates over the class as a whole rather than any particular instance of it. In this case it simply retrieves the current value of the class field numBooks and returns it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Class Method Example (Static Method Example)
class Book {

   static int numBooks;

   String title,author;

   public Book(String a, String t) {
      author=a;
      title=t;
      ++numBooks;
   }

   static int getNumBooks(){return numBooks;}

   public static void main(String[] args) {
      Book b0 = new Book("H Murakami","Kafka on the Shore");
      Book b1 = new Book("Gao Xingjian","Nightwalk");
      System.out.println("Number of books is "+getNumBooks());
   }
}

14 The class method getNumBooks() accesses the class field numBooks and returns it.
In fact this method is another example of an accessor method. It simply returns the value of a class field.

17-19 Two invocations of the Book constructor will cause two instances to be created and numBooks to be incremented appropriately.
The following call to the class method getNumBooks() provides the value of the class field.

* class method Examples