AP Computer Science A – Healdsburg High School 1 Unit 3 - Classes and Objects - Example
AP Computer Science A – Healdsburg High School 2 OOP An OO program models the application as a world of interacting objects. An object can create other objects. An object can call another object’s (and its own) methods (that is, “send messages”). An object has data fields, which hold values that can change while the program is running.
AP Computer Science A – Healdsburg High School 3 Objects Can model real-world objects Can represent GUI (Graphical User Interface) components Can represent software entities (events, files, images, etc.) Can represent abstract concepts (for example, rules of a game, a particular type of dance, etc.)
AP Computer Science A – Healdsburg High School 4 Classes and Objects A class is a piece of the program’s source code that describes a particular type of objects. OO programmers write class definitions. An object is called an instance of a class. A program can create and use more than one object (instance) of the same class.
AP Computer Science A – Healdsburg High School 5 Class Object A blueprint for objects of a particular type Defines the structure (number, types) of the attributes Defines available behaviors of its objects Attributes Behaviors
AP Computer Science A – Healdsburg High School 6 Class: Car Object: a car Attributes: String model Color color int numPassengers double amountOfGas Behaviors: Add/remove a passenger Get the tank filled Report when out of gas Attributes: model = "Mustang" color = Color.YELLOW numPassengers = 0 amountOfGas = 16.5 Behaviors:
AP Computer Science A – Healdsburg High School 7 Class vs. Object A piece of the program’s source code Written by a programmer An entity in a running program Created when the program is running (by the main method or a constructor or another method)
AP Computer Science A – Healdsburg High School 8 Class vs. Object Specifies the structure (the number and types) of its objects’ attributes — the same for all of its objects Specifies the possible behaviors of its objects Holds specific values of attributes; these can change while the program is running Behaves appropriately when called upon
AP Computer Science A – Healdsburg High School Introducing The Vic Class A programmable machine that stores CD’s and moves them around with operator commands.
AP Computer Science A – Healdsburg High School 10 Ex. Write an application program that creates a Vic object and then swaps the CD in its third slot with the CD in its second slot. Assume it has CDs in both slots.