Objects: Example Applications, toString, "this" and public vs. private

What we know so far about objects and classes

Classes allow us to create complex data types, using primitive types


A representation of a Student

What we know so far about objects and classes

Objects are reference types

We are reserving new memory space for s1

s1 is an instance of the Student class

What we know so far about objects and classes

To access or modify a property of an object, put a . after the variable name

We call these properties attributes of a class


What we know so far about objects and classes

We can use the Student class as any other type



Declaring an array of elements of type Student


Each element in comp202_students points an instance of the Student class, in the computer's memory

  • Each position in the array is null by default
  • We need to initialize each position in the array before using it

What we know so far about objects and classes

We can define methods inside a class. Inside class methods, we have acces to class attributes

What we know so far about objects and classes

We can define methods inside a class. Inside class methods, we have acces to class attributes

What we know so far about objects and classes

We can define methods inside a class. Inside class methods, we have acces to class attributes

What we know so far about objects and classes

We can define methods inside a class. Inside class methods, we have acces to class attributes

The toString method

All objects in java share the toString method. By default it returns the Memory Address of the object.

An example - Creating a Course class

  • The Course class
    • A Course has an course name, a course id, and an instructor name
    • A Course has a list of registered students
    • Write a method that assigns to each student a random major_program from { "B.A.", "B.Eng.", "B.Sc.", "B.Comm.", "M.Sc", "Ph.D" }
    • Write a method that counts how many students are enrolled in each program

The this keyword

The this returns a memory reference to the current class

A simple exercise - Creating a 2D Point Class

A simple exercise - Creating a 2D Point Class

Public vs Private

Methods and variables declared as public are accessible from any other java file

Public vs Private

Methods and variables declared as private are accessible from within the class instance only

private methods and variables (members) can only be accessed through getter/setter methods

Public vs Private

Why do we care about declaring things as private

private methods and variables allow the designer of the code to control how the class is used ( to check for correct input, to allow for future modifications of the class, to give different values depending on the state of the program, etc)

Anoter exercise - Creating a 2D Point Class, and using in a Polygon class

Using Point in Polygon

Adding a new Point to vertices

Adding a new Point to vertices

Completing the Polygon class

Resources

/