Section 10.2 WrClasses-WE1-P1
Subgoals for Writing a Class.
-
Name it
-
Differentiate class-level
static
vs. instance/object-level variables -
Differentiate class-level
static
vs. instance/object behaviors/methods -
Define instance variables (that you want to be interrelated)
-
Define class variables
static
as needed -
Create constructor (behavior) that creates initial state of object
-
Overloaded constructor (with as many parameters)
-
public
-
Same name as class
-
No return type
-
Default - no parameters
-
Logic - initialize all variables
-
Repeat as needed, adding parameters
-
-
Create 1 accessor and 1 mutator behaviors per attribute
-
Accessors
-
Name is get_<attr_name>
-
Public
-
Return type same data type as attribute
-
No parameters
-
Logic - return value
-
-
Mutators
-
Name is set_<attr_name>
-
Public
-
Return type is void
-
Parameter is same data type as attribute
-
Logic validates input parameter and sets attribute value
-
-
-
Write toString method
-
public
-
Returns String
-
No parameters
-
Logic - convert needed attributes to a format that can be printed
-
-
Write equals method
-
public
-
Returns boolean
-
Parameter - instance of the class
-
Logic - compare attributes for equity
-
-
Create additional methods as needed
Subsection 10.2.1
Consider writing a class to represent a song on your phone or music player. You need to define the appropriate attributes (data) to store the name of the song, the artist, and length. All songs should be stored in the same format, which should be MP3.
Complete the following class skeleton.
public class SongType {
___A___ ___B___ title;
___C___ ___D___ artist;
___E___ ___F___ length;
___G___ ___H___ final String FORMAT = "MP3";
}
Exercises Exercises
2.
3.
4.
5.
6.
7.
8.
You have attempted 1 of 3 activities on this page.