Class Fields & Data Management

Instance Variables/Fields

  • Instance variables are also known as fields.
  • Fields are parts of a class; they are part of the template from which individual objects are made.
  • They define the attributes that each object will have, such as ID, name, and GPA for a student.
  • The values of these fields can be different for each object.

Referencing Fields

  • Fields are referenced using the dot operator (e.g., student.ID).

Visibility

  • Fields may need to be made publicly visible before they can be accessed from outside the class.

Data Types of Fields

  • Fields can hold various types of data, including primitives, objects, and arrays.
  • Any type that can be stored in a regular variable can also be a field of a class.
  • In languages like JavaScript and Python, values can be dynamically assigned to objects, but in this case, only the fields specified in the class definition can be used, and their types must match the defined types.

Example: Student Class

  • All student objects will have an ID, a name, and a GPA, each with a specified type.

Reading Data

  • Data for the fields can be read in from input (e.g., using console.readline to get the student's name and GPA).
  • The ID could be generated automatically.
  • Example input:
    • Student's name
    • Student's GPA

Data Type Parsing

  • When reading in values, especially for types like floating-point numbers (GPA), it's necessary to parse the input to the correct type using functions like float.Parse.(example: GPA=float.Parse(console.readline)GPA = float.Parse(console.readline)).

Outputting Data

  • The data stored in the fields can be printed out to display the information for each object.
  • A foreach loop can be used to iterate through a collection of objects (e.g., students) and print their information.

Example Output

  • For each student, the ID, name, and GPA can be printed.
    • Example:
      • ID: student.ID
      • Name: student.name
      • GPA: student.GPA

Structuring Data with Classes

  • Classes provide a way to structure data, allowing related information to be grouped together.
  • This makes it easier to manage and work with complex data.

Arrays and Classes

  • Arrays can be used to store collections of objects of a class.
  • This allows for easy management of multiple instances of a class.