TurkuBasicOOPinJava / Week 4: Writing classes /11A Other object methods (beyond get-set)
KaiquanMah's picture
11A Other object methods (beyond get-set)
8b1acba verified
Of course, object methods do not have to be just straightforward methods
for setting and observing attributes.
However, in general, methods do make some use of attributes;
the purpose of public operations on objects is to view and modify the
data content of the object.
Consider the class 'Notebook'.
Since notes are a list, it would be more convenient than a
direct setting method to provide a method for the client to
'add a single note to the notebook':
class Notebook {
private String owner;
private ArrayList<String> notes;
// CONSTRUCTOR
public Notebook(String owner) {
this.owner= owner;
// not from parameter, but initialize an empty list
this.notes= new ArrayList<>();
}
public String getOwner() {
return this.owner;
}
public void addNote(String note) {
this.notes.add(note);
}
// Returns all notes in one string
public String allNotes() {
// join method connects all elements of the list with
// the given separator
// kind of like the opposite of 'split' method
String nb = String.join("\n", notes);
return nb;
}
}
Now it's easier for the customer to use the notebook.
The actual storage format is encapsulated (i.e. hidden from the client).
This means that it doesn't matter if the internal implementation of
the class changes (for example, from a list to a table or a hash table)
as long as the public operations are preserved.
public class Testclass {
public static void main(String[] args) {
Notebook book = new Notebook("Mike Memorizer");
book.addNote("Go to the store!");
book.addNote("Cram for test!");
book.addNote("Watch the news!");
System.out.println(book.allNotes());
}
}
Program outputs:
Go to the store!
Cram for test!
Watch the news!
As another example, consider the class 'Cube'.
In addition to methods for setting and getting the length of a page,
the class could have methods for calculating the area and volume, for example:
class Cube {
private int sidelength;
// constructor
public Cube(int sidelength) {
this.sidelength = sidelength;
}
public int getSidelength() {
return sidelength;
}
public void setSidelength(int sidelength) {
this.sidelength= sidelength;
}
public int Area() {
return sidelength* sidelength* 6;
}
public int Volume() {
return sidelength * sidelength* sidelength;
}
}
Example on using the class:
public class TestClass {
public static void main(String[] args) {
Cube smallCube = new Cube(3);
System.out.println(smallCube.Area());
System.out.println(smallCube.Volume());
Cube largeCube = new Cube(15);
System.out.println(largeCube.Area());
System.out.println(largeCube.Volume());
}
}
Program outputs:
54
27
1350
3375