Object-Oriented Programming Prelim Workbook PDF (2025)

Document Details

Uploaded by Deleted User

Pamantasan ng Cabuyao

2025

John Patrick M. Ogalesco,Janus Raymond C. Tan

Tags

object-oriented programming Java programming programming computer science

Summary

This document is a workbook on object-oriented programming. It focuses on introductory concepts and provides learning outcomes, resources, and lesson discussion on the subject using Java as language tool. The workbook includes examples and explanations of methods and attributes as well as private, public keywords.

Full Transcript

PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 0 OBJECT-ORIENTED PROGRAMMING Prepared by: Asst. Prof. John Patrick M. Ogalesco Asst. Prof. Janus Raymond C. Tan PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING...

PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 0 OBJECT-ORIENTED PROGRAMMING Prepared by: Asst. Prof. John Patrick M. Ogalesco Asst. Prof. Janus Raymond C. Tan PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 1 Introduction to OOP 1 LEARNING OUTCOMES At the end of this lesson, the students should be able to: Identify the components of a class Explain what is a class and object in Object-Oriented Programming Create a simple program using Object-Oriented approach RESOURCES NEEDED For this lesson, you would need the following resources: Laptop or personal computer Java Development Kit (JDK) Java IDE like Eclipse or BlueJ PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 2 LESSON DISCUSSION Object-oriented Programming (OOP) is a programming approach supported by many of the major programming languages such as Java, C#, C++, PHP and Ruby. Real-world entities like a car, an animal, or a person (e.g., a student or teacher) can be created as objects. Even abstract concepts, like a sales transaction, can be modeled as objects. An object has attributes (also known as properties or fields) that describe its state and methods (also known as behaviors) that define its actions. To create an object, the first thing you need to do is to define a class. A class is basically the template or blueprint for your objects. You define the attributes and methods of an object in a class. All objects of that class share the same attributes and methods. Suppose you want to create a class for representing a dog as an object. You can write the program in Java as follows: public class Dog { } The public keyword is an access modifier that defines the visibility of the class. Since the class is public, it can be accessed from any other class, even outside its package. A package is like a folder containing a group of related classes. Packages created by users are called user- defined packages while packages already available in the programming language are called built-in packages. We use packages to avoid name conflicts, and to write a better maintainable code. In the Java programming language, a common example of a built-in package is the java.util which contains the Scanner, LinkedList and Stack classes. There are other access modifiers. We will cover them as we progress with the course. The class keyword must be followed by a valid identifier (the name of the class) to define a class. By convention, class names begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName). In our example, the identifier is Dog since we are talking about dogs. Don’t forget to save the class as Dog.java. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 3 The next step is to create another class (let’s class it Main) that contains the main() method. In simple programs, objects are often created in the main() method for demonstration, testing, or as part of initializing the application. The program for the Main class is presented below: public class Main { public static void main (String args[]) { } } Don’t forget to save the Main class as Main.java. Everything is ready. We can now create an object by following the syntax below: ClassName objectName = new ClassName(); The objectName acts like a variable name. For example, if we want to create an object named dog1, we can do so as follows: Dog dog1 = new Dog(); The process of creating an object is called object instantiation. Let’s update our Main class to include the object instantiation. The updated code is presented below: public class Main { public static void main (String args[]) { Dog dog1 = new Dog(); } } Currently, our code doesn’t do anything except creating an object for the class Dog called dog1. Let’s go back to the Dog class to add some attributes. Attributes (also called properties or fields) describe the quality or state of an object. In the real-world, we often describe dogs based PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 4 on breed and color. Let’s apply this concept to our Dog class. The updated code is presented below: public class Dog { private String breed; private String color; } Attributes are basically variables describing the class. In our example, we declared two String variables: breed and color. Attributes can have different data types depending on what they represent (e.g., weight is float-type attribute). Although not required, it is a best practice that attributes must be declared as private. Attributes with private access modifier cannot be accessed outside the class. Since breed and color are declared inside the Dog class, you cannot access these variables in the Main class. The principle behind this is called encapsulation. Encapsulation is one of the core principles of OOP. Encapsulation ensures that the internal state of an object is hidden from external access, and modifications to the object's state are controlled through methods. As mentioned earlier, the breed and color attributes are not accessible in the main() method. If we want to change the value of these attributes, we need to create a set() method. A set() method (commonly known as “setter”) is a public method used to set or change the value of a private field in a class. The syntax is as follows: public void setAttributeName(dataType parameter) { attributeName = parameter; } For the breed attribute, we can write: public void setBreed(String breed) { this.breed = breed; } PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 5 The setter is named setBreed() to indicate that it represents the breed attribute. A setter must have a parameter. Since we are expecting to accept a value for the breed, the parameter must be a String. In this example, the parameter was named breed which has a conflict with the name of our attribute. To differentiate the two variables, we will use the this keyword. Simply put, this.breed refers to the attribute or the class field while breed (without the this) refers to the parameter. The statement this.breed = breed; sets the value of the attribute equivalent to the value of the parameter. We also need to define the set() method for the color as presented below: public void setColor(String color) { this.color = color; } The updated code for our Dog class is presented below: public class Dog { // Class fields private String breed; private String color; // Set methods public void setBreed(String breed) { this.breed = breed; } public void setColor(String color) { this.color = color; } } Since we already have set methods for the attributes, we can now modify the breed and color of dog1 object in the Main class by passing a value to the parameter of the method. For example, if we want to make dog1 a white-colored pomeranian dog, we can write it as: PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 6 dog1.setColor("white"); dog1.setBreed("pomeranian"); The updated code for the Main class is presented below: public class Main { public static void main (String args[]) { Dog dog1 = new Dog(); dog1.setColor("white"); dog1.setBreed("pomeranian"); } } What if we want to display the values of the attributes? How do we accomplish it? To access the values of private attributes in a class, we can create a public method known as a get() method. A get() method (commonly referred to as a "getter") is a method designed to retrieve and return the value of a private field, ensuring controlled and secure access to the data while maintaining encapsulation. The syntax for the get() method is presented below: public dataType getAttributeName() { return attributeName; } To create a get() method for the breed attribute we could write: public String getBreed(){ return breed; } PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 7 Since it is a get() method for the breed attribute, we named it as getBreed(). The getBreed() method is of type String because the value to be returned (the value of the breed attribute) is a String. The get() methods don’t have parameters since their primary purpose is to return the value of a private attribute without modifying it. You also need to create a get() method for the color attribute as presented below: public String getColor() { return color; } The updated code for the Dog class is presented below: public class Dog { // Class fields private String breed; private String color; // Get and set methods public String getBreed(){ return breed; } public void setBreed(String breed) { this.breed = breed; } public String getColor(){ return color; } public void setColor(String color) { this.color = color; } } PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 8 Notice that the get() and set() methods for every attributes are grouped together for better code readability and organization. We can now retrieve or display the attribute values using the get() methods similar to the one presented below: System.out.print(dog1.getBreed()); System.out.print(dog1.getColor()); Let’s update our Main class to include the code for displaying the attribute values. Let’s add some message to make the output better than just a literal display of values. The updated code is as follows: public class Main { public static void main (String args[]) { Dog dog1 = new Dog(); dog1.setColor("white"); dog1.setBreed("pomeranian"); System.out.print("dog1 is a " + dog1.getColor() + " " + dog1.getBreed()); } } To test the program, we need to run the Main class since the main() method is defined there. The result is similar to the one below: dog1 is a white pomeranian As mentioned earlier, objects have methods (also known as behaviors). Methods define the behaviors or actions that objects of the class can perform. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 9 The syntax for defining a method is presented below: accessModifier dataType methodName (dataType parameter1, … , dataType parameterN) { statements; } The accessModifier defines the visibility of the method. If the method is public (just like in the case of getters and setters), the method can be accessed within the same class, from other classes in the same package, and from classes in different packages (provided the class containing the method is also public). If the method is private, it can only be accessed within the same class. A private method is like a "behind-the-scenes helper." It is used inside a class to perform small tasks that support the main actions of the class, but it is hidden from the outside world. Only the other methods inside the same class can use it. This prevents other parts of the program from directly accessing or interfering with it. The dataType defines the type of value to be returned by the method. For example, if your method intends to compute the sum of two integer numbers and return the sum as the result, the data type of your method must be int. The data type is void if the method will not return a value. This is usually the case for methods that perform actions such as displaying a message or updating the attribute of an object (just like in the case of the set() methods). The methodName is basically the identifier or the name you want to give to your method. For example, if your method is intended to compute the sum of two integer numbers, you can name it as computeSum() or getSum(). Method parameters are variables defined in a method's signature that act as placeholders for the values (called arguments) passed to the method when it is called. They enable methods to receive input data, which the method can use to perform its task. If the method does not need external data, the parameters can be omitted from the method definition. We’re done discussing the important parts of a method. Let’s apply this in our Dog class. Let’s add the bark() method that simulates the dog barking by printing a message to the console. The bark() method is as follows: PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 10 public void bark() { System.out.println("\ndog1 is barking: Woof! Woof!"); } Let’s add another method. Let’s call it eat() method and it will simulate the eating action of a dog. It takes a food parameter to specify what the dog is eating. The eat() method is as follows: public void eat(String food) { System.out.println("dog1 is eating " + food + "."); } Notice that both methods have public access modifier because we want it to be accessible outside the Dog class. Also, both methods have the void datatype since they don’t return a value. They just print messages to the screen. The updated code for the Dog class is as follows: public class Dog { // Class fields private String breed; private String color; // Get and set methods public String getBreed(){ return breed; } public void setBreed(String breed) { this.breed = breed; } public String getColor(){ return color; PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 11 } public void setColor(String color) { this.color = color; } // Class methods public void bark() { System.out.println("\ndog1 is barking: Woof! Woof!"); } public void eat(String food) { System.out.println("dog1 is eating " + food + "."); } } Let’s update the Main class and call our methods. The updated code is as follows: public class Main { public static void main (String args[]) { Dog dog1 = new Dog(); dog1.setColor("white"); dog1.setBreed("pomeranian"); System.out.print("dog1 is a " + dog1.getColor() + " " + dog1.getBreed()); dog1.bark(); dog1.eat("dog food"); } } The output of the program is presented below: dog1 is a white pomeranian dog1 is barking: Woof! Woof! dog1 is eating dog food. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 12 The Calculator Program The calculator program demonstrates a simple use case of Object-Oriented Programming (OOP) by creating a class that encapsulates basic arithmetic operations: addition, subtraction, multiplication, and division. It highlights how methods in a class can be used to perform tasks and interact with external input. The Calculator class acts as a blueprint that defines methods for various operations. It encapsulates the logic for arithmetic operations within a reusable and maintainable structure. The Calculator class has no attributes, get() methods and set() methods in this example. An object of the Calculator class (calc) is created in the main() method. This object is used to call the methods (add(), subtract(), multiply(), divide()), demonstrating how objects interact with their class to perform actions. Calculator.java public class Calculator { // Method to add two numbers public int add(int num1, int num2) { return num1 + num2; } // Method to subtract two numbers public int subtract(int num1, int num2) { return num1 - num2; } // Method to multiply two numbers public int multiply(int num1, int num2) { return num1 * num2; } // Method to divide two numbers public double divide(int num1, int num2) { if (num2 != 0) { return (double) num1 / num2; } else { System.out.println("Error: Division by zero!"); return 0.0; PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 13 } } } Main.java public class Main { public static void main (String args[]) { // Creating an object of the Calculator class Calculator calc = new Calculator(); // Using the object to call methods System.out.println("Addition: " + calc.add(10, 5)); System.out.println("Subtraction: " + calc.subtract(10, 5)); System.out.println("Multiplication: " + calc.multiply(10,5)); System.out.println("Division: " + calc.divide(10, 5)); } } The Circle Program This program demonstrates the creation of a Circle class that calculates diameter and circumference as derived attributes based on the radius. Derived attributes are not stored explicitly in the class but are calculated when needed. This approach avoids redundancy and ensures the values are always consistent with the current radius. In this example, the Circle class has no get() and set() methods. The set() methods for the attributes were grouped together in a single method named setAttributes(). The Circle class has no get() methods. Instead, a displayDetails() method is defined for displaying the attributes. However, if you want to modify and retrieve the attributes individually, you need to create the get() and set() methods. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 14 Circle.java public class Circle { // Attributes (fields) of the Circle class double radius; // Radius of the circle String color; // Color of the circle // Method to set the attributes of the Circle public void setAttributes(double circleRadius, String circleColor) { radius = circleRadius; color = circleColor; } // Method to calculate the diameter (derived from the radius) public double calculateDiameter() { return 2 * radius; } // Method to calculate the circumference (derived from the radius) public double calculateCircumference() { return 2 * Math.PI * radius; } // Method to display the details of the Circle public void displayDetails() { System.out.println("Circle Details:"); System.out.println("Radius: " + radius); System.out.println("Color: " + color); System.out.println("Diameter: " + calculateDiameter()); System.out.println("Circumference: " + calculateCircumference()); } } PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 15 Main.java public class Main { public static void main (String args[]) { // Creating an object of the Circle class Circle myCircle = new Circle(); // Setting the attributes of the circle myCircle.setAttributes(7.0, "Blue"); // Displaying the details of the circle myCircle.displayDetails(); } } Notice that the methods calculateDiameter() and calculateCircumference() for computing the circle’s diameter and circumference, respectively, were not called in the Main class. They were called in the displayDetails() method as part of the output. If you intend not to call them outside the Circle class, the two methods can be declared private. In the given example, the two methods have public access modifier which means these methods can be called in the Main class. SUMMARY Object-Oriented Programming (OOP) is a programming paradigm that models real-world entities using classes, objects, and methods, allowing for modular, reusable, and scalable code. A class is a blueprint for creating objects and defines the attributes (properties) and behaviors (methods) that objects of the class will have. It acts as a template and does not store data itself. An object is an instance of a class, representing a specific implementation of the blueprint. Each object has its own copy of the attributes and can perform actions defined by the class's methods. Objects are created using the new keyword, and their attributes can be assigned real values. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 16 Assessment Task Programming Problem: In a small city, there is a car rental service called "City Wheels." The company needs to manage a fleet of cars, but for now, they only have one car in their fleet. The company needs to track the car’s model, the year it was manufactured, its rental price per day, and its current rental status (whether it is available or not). The company also wants to calculate the total rental price based on the number of days a customer rents the car. Your task is to create a Java program with two classes: 1. Car Class: o Create a Car class with the following private fields: § model (String) to store the car's model. § year (int) to store the year of manufacture. § rentalPricePerDay (double) to store the rental price per day. § available (boolean) to indicate whether the car is available for rent. o Provide getters and setters for all fields to allow access and modification. o Include a method calculateRentalPrice(int days) that returns the total rental price based on the number of days the car is rented. 2. Main Class: o In the main class, create an instance of the Car class representing a single car in the fleet with sample data. o Demonstrate how to check if the car is available and how to rent it for a specific number of days. o The program should calculate the total rental price for a customer based on the number of days they wish to rent the car. o Finally, display the car's rental status after the reservation is made. The objective is to manage a single car’s rental process and keep track of its status and pricing. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 17 Grading Rubric: Criteria Excellent Good Needs Poor Weight Score Improvement Attributes All attributes One attribute Two Three or 1 are correctly is missing or attributes are more identified not missing or attributes are and implemented. not missing or implemented. implemented. not implemented. Methods All methods One method Two required Three or 3 aligned with required by methods more the program the program required by methods requirements specification the program required by are is not specification the program implemented. properly are not specification implemented properly are not or is missing. implemented properly or are implemented missing. or are missing. Code Code is Code is Code is Code is 2 Quality clean, mostly clean functional but difficult to follows and readable, lacks read and naming with some readability or understand conventions, issues in consistent due to poor and includes naming, or formatting. formatting or proper formatting. naming. indentation. PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 18 REFERENCES Book References (Available at the University Library) 3G E-Learning. (2020). Object Oriented Programming 2nd Edition. 3G E-Learning. 3G E-Learning. (2020). Data Structure and Algorithm 2nd Edition. 3G E-Learning. Forouzan, B. A., & Gilberg, R. F. (2020). C++ Programming: An Object-Oriented Approach. McGraw Hill Education. Gorgon, Hurley. (2020). Computer Programming Languages. Willford Press. Hudson, D. (2020). Python Programming for Beginners. Larsen & Keller Srivastava, A. (2020). A Practical Approach to Data Structure and Algorithm with Programming in C. Academic Press. Online Resources Javatpoint. (2021). Java Training. Retrieved July 26, 2023, from https://www.javatpoint.com/java-tutorial Oracle. (2022). The Java Tutorials. Retrieved July 25, 2023, from https://docs.oracle.com/javase/tutorial/index.html Tutorialspoint. (n.d.). Learn Java Programming. Retrieved July 24, 2023, from https://www.tutorialspoint.com/java/ W3schools. (2023). Java Tutorial. Retrieved July 25, 2023, from https://www.w3schools.com/java/default.asp PAMANTASAN NG CABUYAO |OBJECT-ORIENTED PROGRAMMING 19 Research Journals: Bacchiani, L., Bravetti, M., Giunti, M., Mota, J., & Ravara, A. (2022). A Java typestate checker supporting inheritance. Science of Computer Programming, 221. https://doi.org/10.1016/j.scico.2022.102844 Flageol, W., Menaud, E., Guéhéneuc, Y., Badri, M., & Monnier, S. (2023). A mapping study of language features improving object-oriented design patterns. Information and Software Technology, 160. https://doi.org/10.1016/j.infsof.2023.107222 Kong, Q., Siauw, T., & Bayen, A. M. (2021). Object-Oriented programming. In Elsevier eBooks (pp. 121–134). https://doi.org/10.1016/b978-0-12-819549-9.00016-6 Wang, F. (2023). Efficient generation of text feedback in object-oriented programming education using cached performer revision. Machine Learning With Applications, 13. https://doi.org/10.1016/j.mlwa.2023.100481

Use Quizgecko on...
Browser
Browser