660 likes | 673 Views
Learn how objects in software systems function as building blocks, with properties and capabilities, and how instances are created from classes template. Dive into object capabilities, properties, and the distinctions between classes and instances.
E N D
OBJECTS • What are Objects? • Properties and Capabilities (behaviours) • Classes and Instances • Making Instances • A Sample Program Obj ects the object is a road leading over towards the horizon objects are everywhere a world without objects is nothing every object is sacred trust in the object objects rule the world pray to the objects the object is your true master follow the path of the object a Jedi’s strength flows from the object
What are Software Objects? • Building blocks of software systems • program is a collection of interacting objects • objects cooperate to complete a task • to do this, they communicate by sending “messages” to each other • Object model tangible things • school • car • Objects model conceptual things • meeting • date • Objects model processes • finding path through a maze • sorting a deck of cards • Objects have • capabilities (behaviours): what they can do, how they behave • properties : features that describe the objects
Object Capabilities: Actions • Objects have capabilities that allow them to perform actions • objects are smart — they “know” how to do things • an object gets something done only if some other object tells it to use one of its capabilities • Also called behaviors Capabilities can be: • constructors: establish initial state of object’s properties • commands: change object’s properties • queries: provide answers based on object’s properties • Example: trash cans are capable of performing specific actions • constructor: be created • commands: add trash, empty yourself • queries: reply whether lid is open or closed, whether can is full or empty
Object Properties: State • Properties determine how an object acts • some properties may be constant, others variable • properties themselves are objects — they also can receive messages • trash can’s lid and trash are objects Properties can be: • attributes: things that help describe an object • components: things that are “part of” an object • associations: things an object knows about, but aren’t parts of the object • State: all of object’s properties; changes if a property changes • some don’t change, e.g., steering wheel of car • others do, e.g., car’s color • Example: properties of trash cans • attributes: color, material, smell • components: lid, container, trash bag • associations: a trash can can be associated with the room it’s in
Name that Object • What are some capabilities of the objects in this room? • What are some properties of the objects in this room? • Which of these properties are attributes, which are components and which are associations?
Imprints (object instances) Rubber stamp (object class) Classes and Instances • Our current conception: each object corresponds directly to a particular real-life object, e.g., a specific atom or automobile • Disadvantage: too impractical to work with objects this way • may be too many (i.e., modeling all atoms in the universe) • do not want to describe each individual separately, because they may have much in common • Classifying objects factors out commonality • among sets of similar objects • lets us describe what is common once • then “stamp out” any number of copies later
Object Instances • Object instances are individual objects • made from the class template • one class may represent an indefinite number of object instances • making an object instance is called instantiating that object • Shorthand: • class: object class • instance: object instance (not to be confused with instance variable (also called “data field”)) • Different instances of, say, TrashCan class may: • have different color • be at a different location • have different trash inside • So their instance variables (data fields) can have different values • note: object instances contain instance variables (data fields) • two different but related uses of the word instance
instancea instancei instanceb Object Instances (continued) • Individual instances have individual identities • this allows other objects to send messages to a specific object • each is unique, even though it has same capabilities • think of classroom full of students • Note: in Java, the value of instance variable (data field) is always a reference to an instance, not the instance itself • unlike in other programming languages • A reference is just the address in memory where the properties of the instance are stored • also called pointer Properties
Memory Revealed • Every instance is stored in computer’s memory • memory is a set of consecutively numbered storage locations, each containing a byte • instance is stored in contiguous bytes starting at a given location • Instance is identified and referenced by unique address of its starting location where it was created • address looks like 0xeff8a9f4 (hexadecimal notation, base 16) • just like postal address represents actual home 0x00000000 ( vertical representation ) 0x00000001 0x00000002 0x00000080 memory address of instance 1 memory address of instance 2 memory address of instance 3 ( horizontal representation of memory )
Messages for Object Communication • No instance is an island — it must communicate with others to accomplish task • properties let it know about other objects whom it can talk with • Instances send messages to one another to invoke a capability (i.e., to execute a task) • method is code that implements message • we say “call a method” instead of “invoke capability” • Each message requires: • sender: object initiating action • receiver: instance whose method is being called • messagename: name of method being called • optional parameters: more info telling method how to operate • we’ll discuss parameters in detail in a few lectures • Receiver can (but does not need to) send reply • we’ll discuss return types in detail in a few lectures
Encapsulation • Car encapsulates lots of information • quite literally, under hood and behind dashboard • So, you do not need to know how a car works just to use it • steering wheel and gear shift are the interface • engine, transmission, drive train, wheels, . . . , are the (hidden) implementation • Likewise, you do not need to know how an object works to send messages to it • But, you do need to know what messages it understands (i.e., what its capabilities are) • class of instance determines what messages can be sent to it
Public Capability Public Capability Public Capability Public Capability Public Capability Public Capability Views of a Class • Objects separate interface from implementation • object is “black box”; hiding internal workings and parts • interface protects implementation from misuse • Interface: public view • allows instances to cooperate with one another without knowing details • is a contract: list of capabilities and documentation how to use them • Implementation: private view • properties that help capabilities complete their tasks Private Properties Note: private properties shown schematically as literally contained in an object. In reality, they are actually stored elsewhere in memory and referenced by their addresses
Notes About Java Syntax • Reserved words • certain words have a particular meaning in Java and cannot be used for any other purpose • case-sensitive (always all lower case) class public new private extends • Identifiers • names used for classes, methods, and variables • first character must be a letter or underscore • rest may be any combination of letters, numbers, and underscores • but no spaces Professor 4thStreet aPrettyLongName a_pretty_long_name
Making Code More Readable • Naming conventions • suggestions how to name things • they are intended to make code easier to read and understand • add consistency to a program • not enforced by compiler • We use capitalization to distinguish an identifier’s purpose • class names begin with upper case • method and variable names begin with lower case • in the book, instance variable (data field)s start with an underscore • this is not common, and we discourage it because it's less readable • different programmers have different programming style • Use a name that represents the functionality of an object Good Name Professor teachClass professor Poor Name Thing (no role, purpose) doStuff (not specific) p(too cryptic) class: method: instance:
A Complete Program • Here is our first complete Java program: /* * Chapter 1: FirstApplication.java * Displays a red circle on a white background. * The keyword extends will be explained in Chapter 3. */ public class FirstApplication extends wheels.users.Frame { private wheels.users.Ellipse ellipse; public FirstApplication () { ellipse = new wheels.users.Ellipse(); } //magic to let FirstApplication execute public static void main(String[] arguments) { FirstApplication application = new FirstApplication(); } }
3 Steps to Execute Java Program • Editor: write program & store on disk • Eclipse, jGRASP (also called IDE - "Integrated Development Environment") • Creates Program.java (text file) • Compiler: checks for errors & creates Java bytecode • Eclipse does this automatically • jGRASP has a "compile" button to push • Creates Program.class (bytecode file) • Interpreter: puts (loads) Program.class in memory, reads one bytecode at a time, translates each bytecode to machine code, and CPU executes it • Eclipse & jGRASP have a "run" button to push • Program executes
3 Parts of a Computer • CPU – central processing unit • Executes each instruction • Contains IP (instruction pointer) register • Stores address (location in memory) of next instruction • Memory storage unit • Stores instructions & data • Instructions & data must be piped (sent) to CPU and back via a bus (group of wires) • Instructions can be executed faster than they can be moved to the CPU for execution • Know as von Neumann bottleneck • I/O devices • Input and output • Keyboard, monitor, mouse, etc.
Syntax: Declaring a Class • Class declaration tells Java compiler that we define a new class • i.e., we are “declaring” our intent to “define” class that can be used as a template to instantiate object instances • program must include at least one class definition public class FirstApplication extends wheels.users.Frame • Reserved word public means that anyone can create instance of this class • Reserved word class tells Java that we are defining a new class • FirstApplication is name of the class • named because it is our first application (program) • extends wheels.users.Frame means: • extendsthe functionality of an existing class • in this case, we add the ability to create a red ball to the Frame class defined in the users subpackage of package wheels (explained later)
Syntax: Defining a Class • Class definition following declaration tells Java compiler how to make instances of this class and how those instances respond to messages • thus, simply declaring class not enough • we must also definewhat class does (i.e., how it will fulfill its purpose) • Curly braces{} indicate beginning and end of logical block of code; the “code body” — in this case, class definition • represent difference between declaration and definition • code written between curly braces is associated with class declared in front of them public class FirstApplication extends wheels.users.Frame { } • this is an example of empty code block — “nothing” or “null” code is legal, i.e., syntactically correct, and therefore compiles, but does not do anything useful • Java programs are composed of arbitrarily many class definitions • Java code is like dictionary: “declaration” of concept, followed by its definition • no code can appear outside of a class definition
Constructors • Next we need instances of our classes to do something useful • Constructor is special kind of method that is called whenever the class is instantiated (it creates the instance) • another object sends a message that calls constructor • constructor is the first message an object receives • this object cannot receive a constructor message again • establishes initial state of properties of the instance • If a given class doesn't define any constructors, Java automatically makes one for that class • called default constructor • initializes all instance variables (data fields) for instance to their default values • We need to write our own constructor... • when our application is created we want to create new object (a red circle that appears on the screen!)
Syntax: Declaring Constructors • We want to declare constructor for our class: public class FirstApplication extends wheels.users.Frame { public FirstApplication () { } } • This is our first example of method declaration • declares to compiler our intent to define method that implements response to particular message • General syntax notes: • public means any other object can call this constructor • FirstApplication is method’s name • parentheses () indicate that this method doesn't need parameters (explained later) • Constructors have special syntax: • must always have same name as class name • Notice: constructor is declared between curly braces that define class • so constructor is a special capability of the class
Introducing Packages • What does class FirstApplication need in order to be capable of fulfilling its purpose? • A redball on the screen! • This has already been written for you by the textbook’s creators • built by someone else, but usable by anyone • like parts in a catalog • package is a Java catalog • Packages are collections of related classes • library of reusable classes (wheels) • Packages can also contain other packages • “nesting” provides better organization • like sections and sub-sections in catalog
More on Packages • To access classes in another package, must “qualify” class name by package(s) it is in • prepend each package name, separated by periods wheels.users.Frame • Frame is a class in package users, which is a subpackage of wheels package names class name
Object Instantiation • Object instantiation creates an object instance from a particular class • allows other instances to send messages to instance • constructor is first message: makes the instance public FirstApplication () { ellipse = new wheels.users.Ellipse(); } • Reserved word new tells Java to make new object instance, i.e., “call” constructor • fully qualified name of constructor to call is given after new; since constructors have same name as their classes, this defines the class to instantiate • in this case, new Ellipse is created (class in users package which is a subpackage of wheels) • Java calls constructor when object is made • statements defined in constructor are executed • Result of calling constructor is new instance of that class
What about the rest? public static void main(String[] arguments) { FirstApplication application = new FirstApplication(); } To run the program, something must create an instance of class FirstApplication • the Java Virtual Machine (JavaVM) starts the program by calling the special method main • The main method then creates an instance of class FirstApplication • You can think of the main method as the prologue to your application’s constructor • special method that can be called without instantiating an object • it just gets called and then constructs and sets up your application • Every program HAS to have one… it’s your starting point! • it’s a lot of magic! (for now) • FirstApplication is the first thing created when the program is run • for now use wheels.users.Frame, later use something that does less work
Input from user Appropriate GUI component (button, menu, etc.) wheels.users.Frame More about Frames • Frames magically do a lot of work for you • handle input stream of events, i.e., mouse clicks and keyboard presses • send messages to appropriate GUI component to handle event
Syntax: Extending Frame Class • To create your own frame, you don’t have to start from scratch (which would be a huge amount of work) -- instead you can extend, i.e., add on to, a default frame defined previously • Java knows how to create a frame, but not how to create your specific one • also, take advantage of the work frames do for you • Syntax for declaring extension is pretty simple, as we saw earlier: public class FirstApplication extends wheels.users.Frame • Note, we give you a package to help you write your assignments: • wheels: graphics library used for examples in the book • See “Textbook’s Website” link on class website • Sun Microsystems (creators of JAVA) provides many more • See “Java 5.0 API” (Application Programming Interface) link
public static void main(String[] arguments) FirstApplication application = new FirstApplication(); ellipse = new wheels.users.Ellipse(); Steps of Execution • What’s going on inside the Java VM when we start from a main method? • What about static, void, String[] and arguments? • we’ll talk about them in future lectures • for now, just accept that you need them to make your program work inside main inside FirstApplication
Final Code for FirstApplication • Now that we have deconstructed it, let’s look at this code one more time: /* * Chapter 1: FirstApplication.java * Displays a red circle on a white background. * The keyword extends will be explained in Chapter 3. */ public class FirstApplication extends wheels.users.Frame { private wheels.users.Ellipse ellipse; public FirstApplication () { ellipse = new wheels.users.Ellipse(); } //magic to let FirstApplication execute public static void main(String[] arguments) { FirstApplication application = new FirstApplication(); } }
FirstApplication(cont.) • Steps of execution • user starts program by pressing the “Run” button of the IDE (Integrated Development Environment) • method main(…) is called by JavaVM • FirstApplication is instantiated by the new command • constructor FirstApplication() is activated upon instantiation of class FirstApplication • instance of Ellipse is created by activating its constructor • FirstApplication’s constructor is now finished, FirstApplication (and anything constructed in it) runs until program quits (by pressing the “quit” button located at the bottom of the frame)
Class Exercise • Modify class FirstApplication so it displays a rounded red rectangle on a white background. • Check out the wheels package (see “Textbook’s Website” link from class web page) for details on classes & methods
OBJECTS (continued) • Views of a Class • Defining Your Own Class • Declaring Instance Variables (Data Fields) • Declaring Methods • Sending Messages
Example: The ICSMobile • How can we best design and build the ICSMobile? • Think object-oriented: the ICSMobile is an object with properties and capabilities • Create a class to model the ICSMobile and then make instances of that class
Specifications of the ICSMobile • A basic specification ofthe ICSMobile: The ICSMobile should have an engine and wheels so that it can move around. It also should have doors so that people can get in and out. The ICSMobile should have the ability to move forward and backward. It should also be able to turn left and right. • What are the ICSMobile’s properties? • engine, wheels, doors • What are the ICSMobile’s capabilities? • move forward, move backward, turn left, turn right • don’t forget the constructor — all objects have the ability to be constructed (when sent a message to do so by another object) • What does this look like in Java? • remember, properties are represented by instance variables • capabilities are represented by methods • Let’s see...
Simple Syntax for ICSMobile Note: The point of this to show an outline of what a generic class looks like. package machinePackage.carPackage; /** Models a vehicle that can move and turn. */ public class ICSMobile { // instance variables (data fields) private Engine engine; private Door driverDoor; private Door passengerDoor; private Wheel frontDriverWheel; private Wheel rearDriverWheel; private Wheel frontPassengerWheel; private Wheel rearPassengerWheel; public ICSMobile() { // constructor // construct the component objects engine = new Engine(); driverDoor = new Door(); passengerDoor = new Door(); frontDriverWheel = new Wheel(); rearDriverWheel = new Wheel(); frontPassengerWheel = new Wheel(); rearPassengerWheel = new Wheel(); }
Simple Syntax for ICSMobile (cont.) // declare and define methods public void moveForward() { // code to move ICSMobile forward } public void moveBackward() { // code to move ICSMobile backward } public void turnLeft() { // code to turn ICSMobile left } public void turnRight() { // code to turn ICSMobile right } }
ICSMobile Syntax Explained (1 of 5) package machinePackage.carPackage; • package keyword tells Java that this class should be part of a package • in this case, the package (folder) is machinePackage and the subpackage (subfolder) is carPackage • so the code would be stored in the subfolder called carPackage /** ... */ • everything between /* and */ is a block comment • useful for explaining specifics of classes • compiler ignores comments • but we comment for people who want to read our code • class ICSMobile has a kind of block comment called a documentation comment • appears at top of class • explains purpose of class public class ICSMobile { • declares that we are about to create a class named ICSMobile • public indicates that any other object can create instance of this class
ICSMobile Syntax Explained (2 of 5) • Everything associated with class must appear within the curly braces, the body {all instance variables (data fields) and methods; } // no code may appear outside braces // ... • everything on the same line after // is a comment • known as inline comment • describes important features in code private Engine engine; • declares an instance variable named engine of type Engine • reserved word private • indicates that instance variable (data field) will be available only to methods within this class • other objects do not have access to engine • ICSMobile “encapsulates” its engine • remember, properties are objects themselves • every object must be an instance of some class • class of instance variable (data field) is called its type • type determines what messages this property understands
ICSMobile Syntax Explained (3 of 5) • name of instance variable is engine • Note: We don’t follow the book’s coding convention to prefix all instance variables (data fields) with an underscore, “_” • private Door driverDoor, • private Door passengerDoor; • Java allows to declare multiple instance variables of the same type and just separate them with a comma, but we recommend to declare each variable separately • driverDoor and passengerDoor are instance variables of type Door • public ICSMobile() {…} • constructor for class ICSMobile • remember: constructor is first message sent to instance • must have the same identifier as its class • () makes it a method • Standard convention: variable names start with lowercase letter and all new words in the name are capitalized
ICSMobile Syntax Explained (4 of 5) engine = new Engine(); • reserved word new tells Java that you want to make a newinstance • equals sign, =, means variable on left side “gets” value of right side • so value of instance variable engine will be new instance of class Engine • i.e., engine “gets” a new Engine • constructors initialize the new instance • i.e., construct initial state • note: Constructor ICSMobile() refers directly to engine • all methods, including constructor, have direct access to all of their class’ instance variables (data fields) • all other instance variables are initialized in the same way
Another way to initialize ICSMobile • Variables can be initialized where they are declared • Consider our ICSMobile: package machinePackage.carPackage; /** Models a vehicle that can move and turn. */ public class ICSMobile { // instance variables private Engine engine = new Engine(); private Door driverDoor = new Door(); private Door passengerDoor = new Door(); private Wheel frontDriverWheel = new Wheel(); private Wheel rearDriverWheel = new Wheel(); private Wheel frontPassengerWheel = new Wheel(); private Wheel rearPassengerWheel = new Wheel(); public ICSMobile() {} • Advantages of the latter form: • uninitialized variables are often cause of errors, • giving them a value right away is a good practice (see later)! • the code is shorter, more readable • empty constructor can be omitted (Java inserts one)
ICSMobile Syntax Explained (5 of 5) public void moveForward() {…} • declares a method named moveForward • reserved word public indicates this method is visible to anyone • any other object that knows an instance of this class can send it moveForward message • reserved word void means that this method does not return any result • some methods return values to calling method • later we will learn more aboutreturn types • constructor declaration does not need to state return value, it returns the new object instance • moveForward is name of the method • anything inside curly braces is part of method definition’s body • Standard convention: method names start with lowercase letter and all new words in the name are capitalized
ICSMobile • That’s it for the basic skeleton of class ICSMobile! • Now you know how to write a class with properties and capabilities • can declare variables (data fields) and methods • By the end of the course, you will be able to write the full ICSMobile class! • will be able to fully define methods • will add a few more instance variables and change methods a little • but... basic structure will be the same! • Next we look at representation of our three types of properties • components • associations with other objects • attributes
ICSMobile Engine Object Relationships and Diagrams • Our specification says that ICSMobile has an engine, doors, and wheels; these are components • We can say that the ICSMobileis composed of its engine, doors, and wheels • Containment is a way to associate objects with one another • How do you determine containment? • class ICSMobile has an instance variable of type Engine • class ICSMobilecreates an instance of type Engine • therefore, ICSMobileis composed of an Engine • How do we diagram containment? • UML (Unified Modelling Language) engine
In the City… • Suppose we have a City object. • City contains and therefore constructs • parks • schools • streets • cars, e.g., ICSMobiles • Therefore, City can call methods on • parks • schools • streets • ICSMobiles • But, relationship is not symmetric! • Park, School,Street and ICSMobile classes don’t automatically have access to City -- i.e., they can’t call methods on City • How can we provide ICSMobilewith access toCity?
ICSMobile City The Association Relationship • Answer: We associate the ICSMobile with its City • How do you determine the association relationship? • we’ll add to class ICSMobilean instance variable of type City • class ICSMobiledoesn’t create its instance of type City; therefore, City won’t be a component of ICSMobile • we say: class ICSMobile “knows about” City • tune in next lecture to see how to set up an association (“knows about”) relationship in Java • How do we diagram association? • UML (Unified Modelling Language) city
ICSMobile Color color Attributes • The ICSMobile has certain attributes • color, size, position, etc. • Attributes are properties that describe the ICSMobile • we’ll add to class ICSMobile an instance variable of type Color • ICSMobileis described by its Color • different than “is composed of” relationship • class ICSMobiledoesn’t contain its Color, nor is it associated with it • we say: Color is an attribute of class ICSMobile • class ICSMobile may set its own Color or another class may call a method on it to set its Color • actual color of ICSMobile is an attribute, and it is also instance of Color class • all instance variables are instances! • How do we diagram an attribute? • because attributes don’t have the full weight of other object relationships, we just put their type and name in line, without an arrow for the reference
ICSMobile Engine engine Door driverDoor Door passengerDoor Wheel frontDriverWheel Wheel rearDriverWheel Wheel frontPassengerWheel Wheel rearPassengerWheel City city Color color moveForward() moveBackward() turnLeft() turnRight() Class Box • Used to depict schematically a class • rectangle for a class (likeindex card) with name of class at the top • properties of class in next section (types, names of instance variables) • capabilities (methods) of class in bottom section • note: constructor can be assumed • Example of class ICSMobile with the properties discussed:
ICSMobile Color color moveForward() moveBackward() turnLeft() turnRight() Class Diagrams • A class diagram shows how classes relate to other classes • rectangle represents class as class box • important relationships are connected by lines with arrows • important properties have name on top of the lines • attributes have type and identifier (but don’t show references) • UML (Unified Modelling Language) City city <<knows about>> engine <<contains an>> Engine Note: Properties and capabilities of Cityand Engine have been omitted for clarity
Packages and Accessing Classes • Qualified name of ICSMobile • its qualified name is: machinePackage.carPackage.ICSMobile • the qualified name of a class includes the names of all the packages it belongs to (e.g., machinePackage and its sub-package carPackage) • To access a class, you can refer to it by its qualified name • You don’t need to qualify class in same package as current class, or a class that is imported • Engine is in package machinePackage.carPackage • declaration package machinePackage.carPackage; at the top of ICSMobileclass definition makes ICSMobile part of machinePackage.carPackage package • ICSMobile can refer to machinePackage.carPackage.Engine as, simply, Engine • Similarly, you don’t need to qualify an imported class • import wheels.users.Frame; can occur after package declaration • then ICSMobile can use simply Frame