![]() |
![]() |
|
Getters:
We've seen previously, that you can access
the field of an object using the\
syntax:
Song s = new Song( "Happy Birthday", "Patty and Mildred Hill", 31, true ); s.title // evaluates to "Happy Birthday" |
getter method:
String getTitle( Object thiss ) { return thiss.title; } s.getTitle() // evaluates to "Happy Birthday" |
getTitlerather than just change the field directly, we'll start doing that more and more often as we become concerned with having our projects scale up safely and without confusion.
Sometimes we want an object to change over time.
For example,
if a
Song s; s = new Song( "Happy Birthday", "Patty and Mildred Hill", 31, true ); // Returns true: Object120.equals(s, new Song( "Happy Birthday", "Patty and Mildred Hill", 31, true ) ) s.isCopyrighted = false; // Returns false: Object120.equals(s, new Song( "Happy Birthday", "Patty and Mildred Hill", 31, true ) ) |
We often use setter functions
to change a field:
/** Set the isCopyright status of a Song. * @param copyable The new copyright status for the Song to have. */ static void setCopyright( Song thiss, boolean copyable ) { thiss.isCopyrighted = copyable; } // Test that it works (from the Code Pad): setCopyright(s, true); // A *void* function -- must include semicolon in code pad System.out.println( "Actual: " + s ); System.out.println1( "Expect: " + new Song( "Happy Birthday", "Patty and Mildred Hill", 31, false ) ); |
setCopyrightrather than just change the field directly, we'll start doing that more and more often as we become concerned with having our projects scale up safely and without confusion.
setCopyright(s, false); if (Object120.equals(s, new Song( "Happy Birthday", "Patty and Mildred Hill", 31, false ) )) { System.out.println( "(test passed)" ); } else { System.out.println( "Actual: " + s ); ( "Expect: " + new Song( "Happy Birthday", "Patty and Mildred Hill", 31, false ) ); } |
This page licensed CC-BY 4.0 Ian Barland Page last generated | Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |