Structures & Algorithms #4)
CS Dojo
Introduction to Classes and Objects - Part 2
In the previous video, we created a class called "Robot" with attributes such as
name, colour, and weight. We also created two objects of this class, "Tom" and
"Jerry".
Now, let's introduce another class called "Person" with attributes like name,
personality, and sitting. We can create objects of this class as well, such as
"Alice" and "Becky".
To show the relationship between a person and a robot, we can add an attribute
called "robot Owned" to the "Person" class, which will store the robot object
owned by the person.
We can also define methods like "sit-down" and "standup" in the "Person" class
to change the value of the "is Sitting" attribute.
To implement the interaction between the classes, we can set the "robot Owned"
attribute of a person object to a robot object.
Similarly, if we want to show the relationship between robots, we can add an
attribute called "looking at" to the "Robot" class. We can then set the value of
this attribute to another robot object to indicate that one robot is looking at
another robot.
In summary, by adding attributes and setting their values, we can express
relationships between multiple classes and objects.
Implementing the Code
In Java, we can create a class called "Robot" with attributes and a constructor to
create objects. We can also define a method to introduce the object.
Next, we can create a class called "Person" with attributes and a constructor. We
can also define methods to sit down and stand up.
To show the relationship between a person and a robot, we can set the "robot
Owned" attribute of a person object to a robot object.