Week 7, Notes 2

Creating your own objects

Classes like Math provide static methods.  In general, static methods take parameters, use these parameters to calculate a result and return that result.

 

This strategy works fine, because these methods receive all the information they need to do their job from the parameters they are passed at the time they are called.

Java Objects

An object in java is a collection of data in memory with methods attached to it.

 

These methods can all refer to the data in the object without having to have this data passed as parameters.

 

This notion is powerful, because the object can hold onto its data between calls to its methods – something that classes that provide only static methods do not usually do.

Classes as blueprints for objects

Classes tell the java VM (virtual machine) how to build objects at run time.  Classes define:

  1. The data an object stores between calls to its methods.
  2. the methods to which an object can respond.

 

So, classes define a particular kind (or type) of entity, e.g., the Student class defines the data and methods for all student objects. 

 

See labs/l7/Student.java

 

Student objects built from this class store 3 pieces of data:

a String – the student’s name

a String – the student’s id

an int – the number of credits the student has completed.

 

All Student objects respond to the methods shown in Student.java.

 

Notice the methods in Student.java do NOT use keyword static.

 

Creating objects from classes

In JGrasp:

Compile the class.

Click the blue square in the upper middle right of the buttons.

 

Notice on the workbench there is now a blue square that represents an object in memory that is a Student object.

 

R-click the blue square and select invoke method.