Topic 1.6 Running Program with Objects PDF

Summary

This document is a tutorial on running programs with objects in a programming language. It describes how objects can interact and cooperate, using example code. The tutorial covers creating instances of objects and invoking methods, and explains the concept of a runner or driver program as the entry point for an application.

Full Transcript

 CS 002-CS21S1 - Advanced Object-Oriented Programming Pages Topic 1.6 Running Program with Objects...

 CS 002-CS21S1 - Advanced Object-Oriented Programming Pages Topic 1.6 Running Program with Objects Immersive Reader First Semester SY 2024-202… Account Home Syllabus Topic 1.6 Running Program with Objects Dashboard Modules Discussions Courses Assignments Module 1 - Topic 6: Running Programs with Objects Groups Quizzes Chat Calendar BigBlueBu on 44 People As stated from the previous pages, objects are anthropomorphic. Therefore, our classes for LightBulb and BankAccount will never func on on its own. How do we make them work? Inbox Grades 2 Objects now work by coopera ng with other exis ng objects. They interact and cooperate through calling different methods of one another. History Collabora ons Example: In order to make the LightBulb work, it needs other objects that will command it to turn on or turn off. The code below will be able to command the light bulb bulb1 to be turned on. The light bulb object will then respond by performing the necessary ac ons. Help bulb1.turnOn() However, if we try to recall, have we ever created the bulb1 instance? To create the instance, we just need to call the constructor of the class by invoking with the new keyword. The code below will create an instance of a LightBulb object named as bulb1. LightBulb bulb1 = new LightBulb("white", 5); The interpreter will then look for the LightBulb class, call the constructor, pass the string "white" and integer 5 as parameters, and store the instance to the variable bulb1. Runner Class Given now that we have an instance and a command for the LightBulb object, who will be issuing the command? Since there are no other objects available to call it, we can create a Runner or Driver program. A runner or driver program is an object where the main method is defined. This provides the entry point for the applica on. This object can be the ini ator for the interac on of different objects. Runner for LightBulb object import java.util.Scanner; public class Main{ public static void main(String[]args){ LightBulb bulb1 = new LightBulb("white", 5); System.out.println("Turning the light bulb on."); bulb1.turnOn(); System.out.println("Current bulb status: "+bulb1.checkStatus()); Scanner sc = new Scanner(System.in); System.out.print("How many times should we flip the switch? "); int count = sc.nextInt(); for(int i=1; i

Use Quizgecko on...
Browser
Browser