CMSC 202 Classes and Objects: The Basics. Version 9/09 2 Programming & Abstraction All programming languages provide some form of abstraction. –Also called.

Slides:



Advertisements
Similar presentations
Classes and Objects CMSC 202. Version 9/122 Programming & Abstraction All programming languages provide some form of abstraction. – Also called information.
Advertisements

CMSC 202 Fall 2010, Advanced Section Designing with Objects.
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
Designing Classes Chapter 3. 2 Chapter Contents Encapsulation Specifying Methods Java Interfaces Writing an Interface Implementing an Interface An Interface.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 4 Defining Classes I Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Programming Languages and Paradigms Object-Oriented Programming.
Writing Classes (Chapter 4)
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Introduction to Object-Oriented Programming
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Chapter 10 Introduction to Classes
Designing Classes Prelude © 2015 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures and Abstractions with Java, 4e Frank.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Defining Classes I Part A. Class definitions OOP is the dominant programming methodology in use today. OOP is the dominant programming methodology in.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CMSC 202 Java Classes and Object 2nd Lecture. Aug 6, Stack and Heap When your program is running, some memory is used to store local variables.
Objective You will be able to define the basic concepts of object-oriented programming with emphasis on objects and classes by taking notes, seeing examples,
CMSC 202 CMSC 202, Advanced Section Classes and Objects In Java.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Defining Classes I Part B. Information hiding & encapsulation separate how to use the class from the implementation details separate how to use the class.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
OOP Basics Classes & Methods (c) IDMS/SQL News
CMSC 202 Classes and Objects. Aug 6, Programming Languages All programming languages provide some form of abstraction Procedural language (eg C)
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
Chapter 4 Defining Classes I Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CMSC 202 Lesson 8 Classes II. Warmup Declare a class (.h part) named “Cup” It has a data member that says how full it is One method called “Drink” that.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Classes and Objects: Encapsulation
Classes & Objects CMSC 202.
Classes and Objects 2nd Lecture
CMSC 202 Static Methods.
Classes and Objects: Encapsulation
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes and Objects Encapsulation
Defining Classes and Methods
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Defining Classes I Part A.
Defining Classes and Methods
Java Classes and Objects
CMSC 202 Classes and Objects.
CMSC 202 Interfaces.
Classes and Objects Static Methods
Defining Classes and Methods
Classes, Objects and Methods
CMSC 202 Encapsulation Version 9/10.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

CMSC 202 Classes and Objects: The Basics

Version 9/09 2 Programming & Abstraction All programming languages provide some form of abstraction. –Also called information hiding –Separating how one uses a program module from its implementation details Procedural languages: –Data abstraction: using data types –Control abstraction: using functions Object-oriented languages: –Data and control abstraction: using classes Our world is object-oriented.

Version 9/09 3 Making a Sandwich Procedural ham sandwich –grind wheat, bake bread, –kill pig, cure ham –milk cow, make cheese –put ham on bread, put cheese on ham, put bread on cheese Object-oriented ham sandwich –ask baker for bread, –ask butcher for ham, –ask milkman for cheese, –put ham on bread, put cheese on ham, put bread on cheese What are the objects in the object-oriented approach?

Version 9/09 4 What’s a Class? From the dictionary –A kind or category –A set, collection, group, or configuration containing members regarded as having certain attributes or traits in common. From OOP (Rumbaugh, et al) –A group of objects with similar properties, common behavior, common relationships with other objects, and common semantics. –We use classes for abstraction purposes.

Version 9/09 5 Classes All objects are unique. Objects that are identical except for their state can be grouped into a class. –Class of cars –Class of birds –Class of playing cards –Class of bakers

Version 9/09 6 A Class is a Model A class is a model for a group of objects. The focus of the class is the common behavior of the objects the class models. A class’ behavior may also referred to as a service, operation, action, or command. The model also contains common attributes of the objects. –The attributes exist to support the model’s behaviors.

Version 9/09 7 A Class is a Type An Object is a Variable Variables of the class type (objects) may be created just like variables of built-in types. –All bakeries have similar (class) properties. You can create as many objects of the class type as you like. –There is more than one baker in Baltimore. OOP challenge is to define the classes and create the objects that match the problem. –Do we need a farmer class?

Version 9/09 8 Object Interface The requests you can make so an object will do something are determined by its interface. The interface is determined by its class type. IMPORTANT –Do you need to know how a bakery works to get bread? –Who needs to know how a bakery works? Bakery makeBagel() makeBread() sellBagel() sellBread() TYPE INTERFACE

Version 9/09 9 Implementation Code and hidden data in the object that satisfies requests comprise the implementation. –What’s hidden in a bakery? Each request in the interface has an associated method. When a particular request is made, that method is called. In OO-speak we say that you are sending a message to the object, which responds to the message by executing the appropriate code.

Version 9/09 10 Class Definitions You already know –how to use classes and the objects created from them, and –how to invoke their methods. For example, you have already been using the predefined String class. String name = “Fido”; System.out.println(“name length = “ + name.length()); Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/09 11 A Class Is a Type A class is a programmer-defined type. Variables can be declared of a class type. A value of a class variable type is called an object or an instance of the class. –If A is a class, then the phrases “X is of type A“ “X is an object of the class A" “X is an instance of the class A" mean the same thing Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/09 12 The Class Definition A class definition implements the class model. –The class behaviors/services/actions/operations are implemented by class methods. –The class attributes (data items) are called fields or instance variables. In Java, classes are defined in files with the.java extension. The name of the file must match the name of the class defined within it. –e.g. class ‘Baker’ must be in Baker.java Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/09 13 Objects All objects of a class have the same methods. All objects of a class have the same attributes (i.e., name, type, and number). –For different objects, each attribute can hold a different value. –The values of the attributes define the object state, which is what makes each object unique. Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Version 9/09 14 Class Examples What services/behaviors might be appropriate for the following things? –A red-green-yellow traffic light –A garage door opener –A bank account

Version 9/09 15 Anatomy of a Java Class Visibility modifier (More on this later) Name of the class Keyword class publicclass Date1 { } Class body: instance variables, methods NO semi-colon

Version 9/09 16 Instance Variables Defined inside the class definition May be –primitive types –other class types Are accessible by all methods of the class –have class scope Given the services identified for the red-green- yellow traffic light, the garage door opener and the bank account, what instance variables might be defined for each?

Version 9/09 17 Anatomy of a Method Are very much like functions Visibility modifier (More on this later) Name of the method return type publicdouble toCelcius { } Method code: local variables and statements (double fTemp) Optional parameters

Version 9/09 18 Example: A Date Class This class definition goes in a file named Date1.java. public class Date1 { public String month; public int day; public int year; public String toString( ) { return month + “ “ + day + “, “ + year; } These are the (public)“data members” or “instance variables” of the class This is a method definition and its implementation A method may use the class instance variables

Version 9/09 19 Date1 toString Method toString is a method of the Date1 class. –Its definition and implementation are part of the Date1 class. Class methods may –be void or return a value, and –(optionally) have parameters, which may be primitive types passed by value, and/or objects (discussed later). All of a class’ methods have access to all of the class’ instance variables (class scope).

Version 9/09 20 Using Date1 This class definition goes in a file named Date1Demo.java. public class Date1Demo { public static void main( String[ ] args ) { Date1 myDate; myDate = new Date1( ); myDate.month = “July”; myDate.day = 4; myDate.year = 2007; String dateString = myDate.toString( ); System.out.println(dateString); } Create a Date1 object named myDate Give values to the data members Invoke the toString method

Version 9/09 21 Creating the Date1 Object The statement Date1 myDate; defines a variable of type Date1. –But there is no Date1 object yet! The statement myDate = new Date1( ); creates a “new” Date1 object and names it with the variable “myDate”. –Now “myDate” refers to a Date1 object. For convenience, these statements can be combined. Date1 myDate = new Date1( );

Version 9/09 22 “Dot” Notation Public instance variables of an object are referenced using the “dot” operator. myDate.month = “July”; myDate.day = 4; myDate.year = 2007; Instance variables can be used like any other variable of the same type. The set of values stored in all instance variables define the state of the myDate object.

Version 9/09 23 More “Dot” Motation The statement myDate.toString( ); invokes the toString method of myDate, which refers to an object of type Date1. In OO terminology, we say that we are “sending the toString message” to the object referred to by myDate. The object myDate is referred to as the calling object or host object.

Version 9/09 24 Other Date Methods Some other possible services that the Date1 class might provide: incrementDay - changes the date to “tomorrow” DMYString – creates a different string format setDate - initialize/change the year, month, and/or day What others ?

Version 9/09 25 New Date1 Methods // change the month (using an int), day, and year. public void setDate( int newMonth, int newDay, int newYear ) { month = monthString( newMonth ); day = newDay; year = newYear; } // change month number (int) to string - used by setDate public String monthString( int monthNumber ) { switch ( monthNumber ) { case 1: return "January"; case 2: return "February"; case 3: return "March"; case 4: return "April"; case 5: return "May"; case 6: return "June"; case 7: return "July"; case 8: return "August"; case 9: return "September"; case 10: return "October"; case 11: return "November"; case 12: return "December"; default: return “????”; }

Version 9/09 26 Confusion? In the preceding setDate method it’s tempting to define the method using the common terms “month”, “day” and “year” as the parameters. public void setDate( int month, int day, int year) { month = monthString( month );// which month is which? day = day; // which day is which? year = year; // which year is which? } The compiler assumes that all uses of day, month, and year refer to the method parameters and hence this code has no effect.

Version 9/09 27 Calling Object When any class method is called, the instance variables used within the method are assumed to belong to the calling/host object. What the code in setDate is really trying to do is public void setDate( int month, int day, int year) { “calling object”.month = monthString( month ); “calling object”.day = day; “calling object”.year = year; } It’s handy (and sometimes necessary) to have a name for the calling object. In Java, we use the reserved word this as the generic name of the calling object.

Version 9/09 28 Using this So, if we want to name our parameters the same as our instance variables: public void setDate( int month, int day, int year) { this.month = monthString( month ); // notice “this” this.day = day; this.year = year; } Note: Many examples in the text use this technique for class methods. Some Java programmer tools (including Eclipse) use this technique when writing code for you.

Version 9/09 29 this Again Recall the toString method from Date1: public void toString( ) { return month + “ “ + day + “ “ + year; } It’s clear that month, day, and year refer to the instance variables of the calling object because there are no parameters. We could have written: public void toString( ) { return this.month + “ “ + this.day + “ “ + this.year; } If the prefix this is unnecessary, it is usually omitted.

Version 9/09 30 Method Documentation Clear communication with the class user is of paramount importance so that he can –use the appropriate method, and –use class methods properly. Method comments: –explain what the method does, and –describe how to use the method. Two important types of method comments: –precondition comments –post-conditions comments

Version 9/09 31 Preconditions and Postconditions Precondition –What is assumed to be true when a method is called –If any pre-condition is not met, the method may not correctly perform its function. Postcondition –States what will be true after the method executes (assuming all pre-conditions are met) –Describes the effect of the method

Version 9/09 32 A Simple Example The toString method might look something like this: /* PreCondition: none PostCondition: The calling object is returned in the format, */ public void toString( ) { // code here }

Version 9/09 33 Another Example Very often the precondition specifies the limits of the parameters and the postcondition says something about the return value. /* Pre-condition: 1 <= month <= 12 day appropriate for the month 1000 <= year <= 9999 Post-condition: The month, day, and year of the calling object have been set to the parameter values. Returns true if the calling object has been changed. Returns false otherwise */ public boolean setDate(int month, int day, int year) { // code here }

Version 9/09 34 Sample Code Segment Using Date1 Date1 newYears = new Date1( ); newYears.month = “January”; newYears.day = 1; newYears.year = 2008; Date1 birthday = new Date1( ); birthday.month = “July”; birthday.day = 4; birthday.year = 1776; System.out.println(newYears.toString( )); // line 1 System.out.println(birthday.toString( )); // line 2 System.out.println(birthday.monthString(6));// line 3 birthday.setDate( 2, 2, 2002);// line 4 System.out.println(birthday.toString( ));// line 5 newYears.day = 42;// line 6 System.out.println(newYears.toString( ));// line 7

Version 9/09 35 January 42, 2008 It appears that classes allow the user to change the data anytime he or she chooses, possibly making the data invalid. That’s true so far because we have defined our instance variables with public access. This is rarely the case in real applications.