Constructors
Now that we have explored how to identify the needed data and the behaviors of an object, it's time to create a class to define the variables and methods for the data and behaviors.
Class Headers
The head of a class consists of the keyword class and the name of the class. The name of the class should be descriptive and should also be the file name.
You will likely see public in front of class in the class header on the exam. The keyword public allows classes that are not packaged together (in the same folder) to have access to each other. For example, you make a project to play a game that has a Dice class. You want to reuse this Dice class in a new game. You can declare Dice as public and the new program files will be allowed to access it given the file path. At this point, the classes you will be writing are all packaged together in one folder for a project and the use of public is not necessary. You can include it or leave it off.
General Format
Dice Class Example
After the class header, you will need to have an open brace { and at the end of the file, you will need a close brace }.
Instance Variables
Each data value that was identified will need to be defined using a variable. To keep the data of an object safe, we will make the data private. This means the data will not be accessible outside of the class unless there is a method to access the values.
An instance variable is data that is unique for each instance of the class. Each object of the class has its own copy of the variable.
The value for the variable is typically set in the constructor. The variables are only defined at this point.
General Format
Dice Class Format
Constructor
Constructors are used to set the initial state, or value of the instance variables, of an object.
A constructor always has the same name as the class.
A class can have many constructors. The default constructor has no parameters and sets default values to the instance variables. Constructors can also contain parameters that can be used to set the initial value, or state, of the instance variables.
When no consturctor is written, Java provides a default constructor where the instance variables are assigned default values based on their types.
intvariables are assigned0.doublevariables are assigned0.0.booleanvariables are assignedfalse.charvariables are assigned a null character.- reference types are assigned
null.
General Format
Dice Class Constructor Format
Your Turn
|
Grab a Piece of Paper, Let's Try It! |
|