140 likes | 236 Views
Variables and Inheritance Part 1. Alice. Review: Properties. A class defines properties for its own kind of object. When an object is created (instantiated), it receives its own set of properties. State. Each property stores some information about the object. Examples: vehicle
E N D
Review: Properties • A class defines properties for its own kind of object. • When an object is created (instantiated), it receives its own set of properties.
State • Each property stores some information about the object. • Examples: vehicle isShowing • The set of information about the object is called the state of the object.
State Change • Instructions in our program code generally cause a change in a property value -- a state change. • For example, a set instruction can be used to change the color of an object.
Class-level Variables • New variables can be added to the properties list of an object. • class-level • The value of the variable can be changed • We say the variable is mutable. • This extends the capability of an object to track state changes.
Inheritance • If the object (with its new variable) is saved out and given a new name, a new class is created. • This is an example of inheritance. • The new class inherits all the properties and methods (move, turn, roll, etc.) of the original class. • Also,the new class has the newly declared variable and an extended capability to track state changes. • In this session, we will look at a simple example of adding a new class-level variable and inheritance.
Example • A switch is potentially useful as a controller for an animation • switch handle up animation running • switch handle down animation not running • The problem is that the switch does not have a built-in property to track whether the switch handle is up or down.
Creating a new variable • Create a new class-level variable named isOn. • The isOn variable is declared to be a Boolean type. • The value is initialized to true.
On-off Controller Storyboard • The switch will act as an on-off controller. • When the user clicks on the switch, the handle will turn in the opposite direction to provide a visual cue. • A visual cue is helpful because variables are not visible. click: If isOn is true Do together set isOn to false turn the handle forward Else Do together set isOn to true turn the handle backward
switch.click isOn property value is Boolean, so we don't need to write switch.isOn == true
Save out • Save out the switch as a new class. • Rename the object (we used onOffSwitch) • Right-click on the object name and select save object…
Import • Now you can add an instance of the newly created class to a new world.
Event • An instance of the new class has • all the built-in properties and methods of the original Switch class, plus • isOn variable • click method • Still, you must use the Events editor to link a mouse-click event to the click method.