Questions
Give an example of a class and an example of an object. Describe what a class is, what an object is, and how they are related. Use your examples to illustrate the descriptions.
1. Descriptions
Class: A class is like a factory or a blueprint, and we can use it to define variables and create objects. To declare a class, we start with public, then class, then the name of the class, finally, the body of the class in {}. In the body of the class, it can include static member variables, instance variables, static methods, instance methods, and constructors (Seiter & Palmer, 2020).
Object: An object is an instance of a class. In other words, an object is a collection of data and methods manipulating these data (Downey, 2019). More specifically, objects are created by the non-static portions of classes, and they have attributes and behaviors. The Attributes and behaviors correspond to instance variables and instance methods in a class, respectively. The instance variables store the data for an object, and the instance methods allow objects to manipulate these data (Seiter & Palmer, 2020).
Relation: The non-static portions of classes are used to create objects. The object’s attributes correspond to the class’s instance variables, and the object’s behaviors correspond to the class’s instance methods. A class can have many objects with the same structure (Eck, 2019).
2. Examples
Codes:
1 | package discussion_assignment; |
Outputs:
1 | name: banana, color: yellow |
Explanation:
In the above example, I created a class Fruit. It has two instance variables: name and color. Besides, I rewrote the constructor. This constructor has two parameters: initName and initColor. Hence, I can initialize the instance variables name and color when I use this constructor to create objects. In addition, I defined an instance method print(), which is used to print the fruit information.
To create new objects and test instance methods, I defined a main() method in the class. In the main(), I created three different objects: fruit1, fruit2, and fruit3. Then, I used the three objets to call the print() method respectively to output the fruit information owned by the different objects.
As we can see, the fruit class is a factory, which has instance variables and instance methods. And the fruit objects are created by the Fruit class. Different fruit objects store specific fruit data and methods to print these data. In addition, one Fruit class can create multiple objects, and these objects have the same structure.
Word count: 466
References
1.Downey, A.B. & Mayfield, C. (2019). Think Java (2nd ed.). Green Tea Press.
https://open.umn.edu/opentextbooks/formats/331
2.Eck, D. J. (2019). Introduction to Programming Using Java.
http://math.hws.edu/javanotes