© 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods.

Slides:



Advertisements
Similar presentations
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
Advertisements

Lecture 2 Calling and Defining Methods in Java. Introduction ●Calling and defining methods ●Declaring and defining a class ●Instances of a class ●The.
 2005 Pearson Education, Inc. All rights reserved Introduction.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
Introduction to C Programming
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Inheritance Inheritance Reserved word protected Reserved word super
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
Road Map Introduction to object oriented programming. Classes
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Week 4 Recap CSE 115 Spring Formal Parameter Lists Comma-separated list of formal parameters Formal parameters are listed giving the type of the.
Getting Started with Java
© 2006 Pearson Education Using Objects 1 of 32 USING OBJECTS What are Objects? Properties and Capabilities Classes and Instances Making Instances A Sample.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
CSE 115 Week 4 February 4 - 8, Monday Announcements Software installation fest Tuesday & Wednesday 4-7 in Baldy 21. Software installation fest Tuesday.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Introduction to C Programming
Week 3 Recap CSE 115 – Fall Java Source Code File Made up of: Package declaration Class definition.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Writing Classes (Chapter 4)
PARAMETERS Making Messages Specific Setting Up Associations Actual and Formal Parameters Return Types Accessor and Mutator Methods.
1.  A method describes the internal mechanisms that actually perform its tasks  A class is used to house (among other things) a method ◦ A class that.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Classes CS 21a: Introduction to Computing I First Semester,
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Local Variables Garbage collection. © 2006 Pearson EducationParameters2 of 10 Using Accessors and Mutators Together What if you want to get a property.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to programming in the Java programming language.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
1/43 Andries van Dam  /15/15 Lecture 2 Calling and Defining Methods in Java.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Programs and Classes A program is made up from classes Classes may be grouped into packages A class has two parts static parts exist independently Non-static.
SE-1010 Dr. Mark L. Hornick 1 Java Programming Basics.
Chapter 4 Introduction to Classes, Objects, Methods and strings
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 CSC241: Object Oriented Programming Lecture No 02.
Working With Objects Tonga Institute of Higher Education.
© 2006 Pearson EducationMaking Objects 1 of 36 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
More about Java Classes Writing your own Java Classes More about constructors and creating objects.
Variables in C Topics  Naming Variables  Declaring Variables  Using Variables  The Assignment Statement Reading  Sections
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
CMSC 104, Version 8/061L09VariablesInC.ppt Variables in C Topics Naming Variables Declaring Variables Using Variables The Assignment Statement Reading.
Object Oriented Programming Object and Classes Lecture 3 MBY.
Java Programming Fifth Edition Chapter 1 Creating Your First Java Classes.
OBJECTS Obj ects What are Objects?
Chapter 3: Using Methods, Classes, and Objects
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 3 Introduction to Classes, Objects Methods and Strings
Variables ICS2O.
Classes and Objects.
Statements and expressions - java
Classes, Objects, Methods and Strings
Tonga Institute of Higher Education
Object Oriented Programming in java
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

© 2006 Pearson Education Making Objects 1 of 19 MAKING OBJECTS Views of a Class Defining Your Own Class Declaring Instance Variables Declaring Methods Sending Messages

© 2006 Pearson Education Making Objects 2 of 19 Example: The CSMobile How can we best design and build the CSMobile? Think object-oriented: the CSMobile is an object with properties and capabilities Create a class to model the CSMobile and then make instances of that class

© 2006 Pearson Education Making Objects 3 of 19 Specifications of the CSMobile A basic (ok, ridiculously simple) specification of the CSMobile: The CSMobile 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 CSMobile should have the ability to move forward and backward. It should also be able to turn left and right. What are the CSMobile’s properties? – engine, wheels, doors What are the CSMobile’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...

© 2006 Pearson Education Making Objects 4 of 19 Simple Syntax for CSMobile Note: The point of this to show an outline of what a generic class looks like. Some functionality has been elided with // comments. package demos.car; /** Models a vehicle that can move and turn. */ public class CSMobile { // instance variables private Engine engine; private Door driverDoor; private Door passengerDoor; private Wheel frontDriverWheel; private Wheel rearDriverWheel; private Wheel frontPassengerWheel; private Wheel rearPassengerWheel; public CSMobile() { // 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(); }

© 2006 Pearson Education Making Objects 5 of 19 Simple Syntax for CSMobile (cont.) // declare and define methods public void moveForward() { // code to move CSMobile forward } public void moveBackward() { // code to move CSMobile backward } public void turnLeft() { // code to turn CSMobile left } public void turnRight() { // code to turn CSMobile right } }

© 2006 Pearson Education Making Objects 6 of 19 CSMobile Syntax Explained (1 of 5) package demos.car; – package keyword tells Java that this class should be part of a package – in this case, package is d emos.car /**... */ – 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 CSMobile has a kind of block comment called a header comment appears at top of class explains purpose of class public class CSMobile { – declares that we are about to create a class named CSMobile – public indicates that any other object can create instance of this class

© 2006 Pearson Education Making Objects 7 of 19 CSMobile Syntax Explained (2 of 5) Everything associated with class must appear within the curly braces, the body { //all instance variables 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 will be available only to methods within this class other objects do not have access to engine CSMobile “encapsulates” its engine – remember, properties are objects themselves every object must be an instance of some class class of instance variable is called its type – type determines what messages this property understands

© 2006 Pearson Education Making Objects 8 of 19 CSMobile 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 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 CSMobile() {…} – constructor for class CSMobile – 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

© 2006 Pearson Education Making Objects 9 of 19 CSMobile Syntax Explained (4 of 5) engine = new Engine(); – reserved word new tells Java that you want to make a new instance – 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 CSMobile() refers directly to engine all methods, including constructor, have direct access to all of their class’ instance variables – all other instance variables are initialized in the same way

© 2006 Pearson Education Making Objects 10 of 19 Another way to initialize CSMobile Variables can be initialized there where they are declared Consider our CSMobile : package demos.car; /** Models a vehicle that can move and turn. */ public class CSMobile { // 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 CSMobile() {} 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)

© 2006 Pearson Education Making Objects 11 of 19 CSMobile Syntax Explained (5 of 5) public void moveForward() {…} –d–declares a method named moveForward –r–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 –r–reserved word void means that this method does not return any result some methods return values to calling method later we will learn more about return types constructor declaration does not need to state return value, it returns the new object instance –m–moveForward is name of the method –a–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

© 2006 Pearson Education Making Objects 12 of 19 CSMobile That’s it for the basic skeleton of class CSMobile ! Now you know how to write a class with properties and capabilities – can declare variables and methods By the end of the course, you will be able to write the full CSMobile 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

© 2006 Pearson Education Making Objects 13 of 19 Object Relationships and Diagrams Our specification says that CSMobile has an engine, doors, and wheels; these are components We can say that the CSMobile is composed of its engine, doors, and wheels Containment is a way to associate objects with one another How do you determine containment? – class CSMobile has an instance variable of type Engine – class CSMobile creates an instance of type Engine – therefore, CSMobile is composed of an Engine How do we diagram containment? CSMobile engine Engine

© 2006 Pearson Education Making Objects 14 of 19 In the City… Suppose we have a City object. City contains and therefore constructs – parks – schools – streets – cars, e.g., CSMobiles (hey, why not?) Therefore, City can call methods on – parks – schools – streets – CSMobiles But, relationship is not symmetric! Park, School, Street and CSMobile classes don’t automatically have access to City -- i.e., they can’t call methods on City How can we provide CSMobile with access to City ?

© 2006 Pearson Education Making Objects 15 of 19 The Association Relationship Answer: We associate the CSMobile with its City How do you determine the association relationship? – we’ll add to class CSMobile an instance variable of type City – class CSMobile doesn’t create its instance of type City ; therefore, City won’t be a component of CSMobile – we say: class CSMobile “knows about” City – tune in next time to see how to set up an association (“knows about”) relationship in Java How do we diagram association? CSMobile city City

© 2006 Pearson Education Making Objects 16 of 19 Attributes The CSMobile has certain attributes – color, size, position, etc. Attributes are properties that describe the CSMobile – we’ll add to class CSMobile an instance variable of type Color – CSMobile is described by its Color – different than “is composed of” relationship – class CSMobile doesn’t contain its Color, nor is it associated with it – we say: Color is an attribute of class CSMobile – class CSMobile may set its own Color or another class may call a method on it to set its Color – actual color of CSMobile 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 CSMobile Color color

© 2006 Pearson Education Making Objects 17 of 19 Class Box Used to depict schematically a class – rectangle for a class (like index card) with name of class at the top – properties of class in next section (types, names of instance variables) – capabilities of class in bottom section note: constructor can be assumed Example of class CSMobile with the properties discussed: CSMobile Engine engine Door driverDoor Door passengerDoor Wheel frontDriverWheel Wheel rearDriverWheel Wheel frontPassengerWheel Wheel rearPassengerWheel City city Color color moveForward() moveBackward() turnLeft() turnRight()

© 2006 Pearson Education Making Objects 18 of 19 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) City > Engine > Note: Properties and capabilities of City and Engine have been elided for clarity city engine CSMobile Color color moveForward() moveBackward() turnLeft() turnRight()

© 2006 Pearson Education Making Objects 19 of 19 Packages and Accessing Classes Like BouncingBall, CSMobile is in package demos But unlike BouncingBall, it is in a different sub-package – so its qualified name is: demos.car.CSMobile – the qualified name of a class includes the names of all the packages it belongs to (e.g., demos and its sub-package car ) 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 demos.car – declaration package demos.car; at the top of CSMobile class definition makes CSMobile part of demos.car package – thus CSMobile can refer to demos.car.Engine as, simply, Engine Similarly, you don’t need to qualify an imported class – import wheels.users.Frame; can occur after package declaration – then CSMobile can use simply Frame

© 2006 Pearson Education Making Objects 20 of 19 Working With Variables Variables in Java are like variables in math – hold single (reference to a) value that can vary over time – but need to have previously defined value to be used Remember CSMobile ? Creating an instance variable was done in two parts 1. declaration: private Engine engine; 2. initialization: engine = new Engine(); What is value of engine before step 2? What would happen if step 2 were omitted? Java gives all variables a default value of null – i.e., it has no useful value – null is another reserved word in Java – it means a non-existent memory address

© 2006 Pearson Education Making Objects 21 of 19 Uninitialized Variables and null If you forget to give your variables initial values, Java VM will “reward” you with a runtime error in the form of a NullPointerException – runtime errors are problems that occur while your program is running – i.e., your program compiled successfully, but it does not execute successfully – for now, when runtime errors occur, your program is usually stopped by Java VM NullPointerException – if you get such an error, make sure you have initialized all of your object’s instance variables! – most common occurrence of a NullPointerException is trying to send a message to an uninitialized variable WATCH OUT!

© 2006 Pearson Education Making Objects 22 of 19 Assigning Values to Variables Assignment provides a way to change the value of variables – replaces current value of variable with new value – example: engine = new Engine(); – we say: engine “gets” a new instance of class Engine As we’ve seen, equals sign, =, is Java’s syntax for assignment – variable on left side of equals “gets” value of right side – not like equals in Math! (which denotes equality of left- and right-hand sides) Using = with new – calls the constructor of the class – constructor results in new instance of class – new instance is value assigned to variable Using = without new – assigns from one value to another – ex: exteriorColor = interiorColor; – makes the exterior color have the same value as the interior color

© 2006 Pearson Education Making Objects 23 of 19 Working With Methods We know how to declare methods, but how do we call them? How can we send messages between objects? Syntax is variableIdentifier.methodIdentifier(); public class City { private CSMobile csMobile; public City() { csMobile = new CSMobile(); csMobile.moveForward(); } } Sending a message (“calling moveForward on csMobile ”) causes code associated with method to be executed csMobile.moveForward() is a method call csMobile is message’s receiver (one being told to move) dot (“. ”) separates receiver from message name moveForward is name of message to be sent () denotes parameters to the message more on parameters next lecture! woo hoo!