Memory Address
|
Variable Type
|
Variable name
|
Value
|
@1001
|
Student
|
s1
|
null
|
@1001
|
int[]
|
array
|
null
|
No new
memory gets reserved for s1
or array
Using a class in Arrays
We can now use Student
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
The constructor method
Defines some default code that is executed when we create a variable of our class
Declaring variable of type Student
calls the constructor method of Student
s1
is an instance of the Student
class
What are class methods?
We can execute code that depends on the properties of an object
A representation of a Student
What are class methods?
We can execute code that depends on the properties of an object
A representation of a Student
Class method syntax
Remove the keyword static
, from the method declaration
Class method syntax
Remove the keyword static
, from the method declaration
An object instance can access its class attributes inside a class method
Method overloading
Declaring multiple class methods with the same name
and return type
Must have different input arguments
E.g multiple constructors
Method overloading
Declaring multiple class methods with the same name
and return type
Must have different input arguments
E.g multiple constructors
Method overloading
Declaring multiple class methods with the same name
and return type
Must have different input arguments
E.g multiple constructors
An example - Creating a Course class
- The
Course
class
- A
Course
has an course name, a course number, 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
A simple exercise - Creating a 2D Point Class
- The
Point
class
- A
Point
has two coordinates: call them x
and y
- The coordinates should be real numbers (
double
type)
- Write a class method that computes the distance to another
Point
A harder exercise - Creating a 2D Point Class, and using in a Polygon class
- The
Polygon
class
- A
Polygon
has a list of Point
objects; its vertices.
- Write a class method that adds a new vertex to a polygon
- Write a class method that returns
true
if the Polygon
is equilateral
- Write a class method that returns
true
if the Polygon
is regular
- Write a class method that returns the area of a polygon using the Shoelace Algorithm
/