class constructor
Because we've made the field variables private, we need another way to assign values to them. One way to do this is with something called a constructor. This is a method you can use to set initial values for field variables. When the object is created, Java calls the constructor first. Any code you have in your constructor will then get executed. You don't need to make any special calls to a constructor method - they happen automatically when you create a new object.Constructor methods take the same name as the class. Add the following constructor to your StudentResults class:
StudentResults aStudent = new StudentResults( "Bill
Gates", "A" );
When the object is created, the values "Bill Gates" and "A"
will be handed over to the constructor.However, it's a good idea to just set some default values for your field variables. These values will then be assigned when the object is created. Add the following to your constructor:
In the next part, we'll take a look at accessing class variables.
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment