Academic Java    Java Tutorial  >  Classes  >  instance 'accessor' methods

instance 'accessor' methods Example

Java instance 'accessor' methods EXAMPLE output This program defines the class Book with two fields, one for a book's author, the other for a book's title.

Two instance methods are defined. They are accessor methods. That is, they simply return the value of an instance field. One returns the author field, the other the title field.

By convention, accessor methods use the prefix get before the name of the field to which they refer, which gives rise to them also being known as getter methods.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Instance 'Accessor' Methods Example 2
class Book {

   String author, title;

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

   public String getAuthor() {return author;}
   public String getTitle() {return title;}

   public static void main(String[] args) {
      Book b0 = new Book("J Kay","Elroy's gift");
      Book b1 = new Book("A Bean","The sea");
      System.out.println(b0.getTitle() + " by " + b0.getAuthor());
      System.out.println(b1.getTitle() + " by " + b1.getAuthor());
   }

}

4 These are the fields to which the accessor methods refer.

11-12 These are the two accessor methods.

17-18 The accessor methods are called to provide field values.

* instance methods Examples