Designing Classes Eric Roberts CS 106B January 16, 2015.

Slides:



Advertisements
Similar presentations
Collection Classes Eric Roberts CS 106B January 16, 2013 (Part 2: Maps, Sets, and Lexicons)
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Wednesday, 10/2/02, Slide #1 CS 106 Intro to CS 1 Wednesday, 10/2/02  QUESTIONS (on HW02 – due at 5 pm)??  Today:  Review of parameters  Introduction.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Guide To UNIX Using Linux Third Edition
Chapter 13: Object-Oriented Programming
Functions in C++ Eric Roberts CS 106B January 9, 2013.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Computer Science 111 Fundamentals of Computer Programming I Working with our own classes.
CS Introduction to Data Structures Spring Term 2004 Franz Hiergeist.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Chapter 11: Abstract Data Types Lecture # 17. Chapter 11 Topics The Concept of Abstraction Advantages of Abstract Data Types Design Issues for Abstract.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Classes (Chapter ) Classes (Chapter ) Data with natural operations Classes Using Classes.
Lecture 4 CS140 Dick Steflik. Reading Keyboard Input Import java.util.Scanner – A simple text scanner which can parse primitive types and strings using.
Chapter 15 - C++ As A "Better C"
Chapter 12 Classes and Abstraction
Chapter 1.2 Introduction to C++ Programming
Object-Oriented Concepts
Classes and Objects Introduced
Programming what is C++
Classes (Part 1) Lecture 3
Classes C++ representation of an object
Chapter 1.2 Introduction to C++ Programming
Templates.
Introduction to C++ Systems Programming.
Expression Trees Eric Roberts CS 106B March 4, 2013.
(Part 2: Maps, Sets, and Lexicons)
Inheritance and Polymorphism
A First C++ Class – a Circle
Functions in C++ Eric Roberts CS 106B January 7, 2015.
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
More about OOP and ADTs Classes
Chapter 4: Writing Classes
CS212: Object Oriented Analysis and Design
Creating and Using Classes
Can perform actions and provide communication
Chapter 8: Introduction to High-Level Language Programming
Understanding Inheritance
Chapter 3 Introduction to Classes, Objects Methods and Strings
Can perform actions and provide communication
Name: Rubaisha Rajpoot
Week 6 Object-Oriented Programming (2): Polymorphism
More about OOP and ADTs Classes
Classes and Objects.
Can perform actions and provide communication
Building Java Programs
Outline Anatomy of a Class Encapsulation Anatomy of a Method
COP 3330 Object-oriented Programming in C++
Introduction to Data Structure
Defining Classes and Methods
Classes C++ representation of an object
Lecture 8 Object Oriented Programming (OOP)
Classes and Objects Systems Programming.
Introduction to Classes and Objects
Presentation transcript:

Designing Classes Eric Roberts CS 106B January 16, 2015

Optional Movie Martin Luther King, Jr. “I Have a Dream”  Gates B-12  And so even though we face the difficulties of today and tomorrow, I still have a dream. It is a dream deeply rooted in the American dream. I have a dream that one day this nation will rise up and live out the true meaning of its creed: “We hold these truths to be self-evident, that all men are created equal.” Martin Luther King, Jr. “I Have a Dream”  Gates B-12  Monday, January 19 2:15 P.M.

Outline Anagram exercise from last time 1. Structures 2. Representing points using a structure 3. Classes and objects 4. Overloading operators 5. Constructors 6. Representing points using a class 7. The TokenScanner class 8.

Exercise: Finding Anagrams Write a program that reads in a set of letters and sees whether any anagrams of that set of letters are themselves words: FindAnagrams ehprsyz Enter tiles: zephyrs aeinstr Enter tiles: anestri nastier ratines retains retinas retsina stainer stearin Generating all anagrams of a word is not a simple task. Most solutions require some tricky recursion, but can you think of another way to solve this problem? Hint: What if you had a function that sorts the letters in a word. Would that help? Generating all anagrams of a word is not a simple task. Most solutions require some tricky recursion, but can you think of another way to solve this problem? Hint: What if you had a function that sorts the letters in a word. Would that help?

Structures All modern higher-level languages offer some facility for representing structures, which are compound values in which the individual components are specified by name. Given that C++ is a superset of the older C language, it is still possible to define classic C structures, which are defined using the following syntactic form: struct typename { declarations of fields }; This definition creates a type, not a variable. If you want to declare variables of the structure type, you use the type name just as you would with any other declaration.

Representing Points Using a Structure One of the simplest examples of a data structure is a point, which is composed of an x and a y component. For most graphical devices, coordinates are measured in pixels on the screen, which means that these components can be integers, since it is impossible to illuminate a fraction of a pixel. struct Point { int x; int y; }; This definition allows you to declare a Point variable like this: Point pt; Given the variable pt, you can select the individual fields using the dot operator (.), as in pt.x and pt.y.

Classes and Objects Object-oriented languages are characterized by representing most data structures as objects that encapsulate representation and behavior in a single entity. In C, structures define the representation of a compound value, while functions define behavior. In C++, these two ideas are integrated. As in Java, the C++ object model is based on the idea of a class, which is a template describing all objects of a particular type. The class definition specifies the representation of the object by naming its fields and the behavior of the object by providing a set of methods. New objects are created as instances of a particular class.

A Note on Inheritance As you know if you’ve studied other object-oriented languages such as Java, classes form hierarchies in which subclasses inherit the behavior and representation of their superclass. Inheritance also applies in C++, although the model is more complex, primarily because C++ allows classes to inherit from more than one superclass. This property is called multiple inheritance. Partly because of this additional complexity and partly because C++ makes inheritance harder to use, CS 106B postpones the discussion of inheritance until later in the quarter, focusing instead on the use of classes for encapsulation.

The Format of a Class Definition In C++, the definition of a class typically looks like this: class typename { public: prototypes of public methods private: declarations of private instance variables prototypes of private methods }; The entries in a class definition are divided into two categories: A public section available to clients of the class A private section restricted to the implementation

Implementing Methods A class definition usually appears as a .h file that defines the interface for that class. The class definition does not specify the implementation of the methods exported by the class; only the prototypes appear. Before you can compile and execute a program that contains class definitions, you must provide the implementation for each of its methods. Although methods can be implemented within the class definition, it is stylistically preferable to define a separate .cpp file that hides those details. Method definitions are written in exactly the same form as traditional function definitions. The only difference is that you write the name of the class before the name of the method, separated by a double colon. For example, if the class MyClass exports a toString method, you would code the implementation using the method name MyClass::toString.

Overloading Operators One of the most powerful features of C++ is the ability to extend the existing operators so that they apply to new types. Each operator is associated with a name that usually consists of the keyword operator followed by the operator symbol. When you define operators for a class, you can write them either as methods or as free functions. Each styles has its own advantages and disadvantages. For more details, you should look at the Rational class in Chapter 6. My favorite operator to overload is the << operator, which makes it possible to print values of a type on an output stream. The prototype for the overloaded << operator is ostream & operator<<(ostream & os, type var)

Constructors In addition to method prototypes, class definitions typically include one or more constructors, which are used to initialize an object. The prototype for a constructor has no return type and always has the same name as the class. It may or may not take arguments, and a single class can have multiple constructors as long as the constructors have different parameter sequences. The constructor that takes no arguments is called the default constructor. If you don’t define any constructors, C++ will automatically generate a default constructor with an empty body. The constructor for a class is always called when you create an instance of that class, even if you simply declare a variable.

The point.h Interface /* * File: point.h * ------------- * This interface exports the Point class, which represents a point * on a two-dimensional integer grid. */ #ifndef _point_h #define _point_h #include <string> class Point { public:

The point.h Interface /* * Constructor: Point * Usage: Point origin; * Point pt(xc, yc); * ------------------------ * Creates a Point object. The default constructor sets the * coordinates to 0; the second form sets the coordinates to * xc and yc. */ Point(); Point(int xc, int yc); /* * File: point.h * ------------- * This interface exports the Point class, which represents a point * on a two-dimensional integer grid. */ #ifndef _point_h #define _point_h #include <string> class Point { public:

The point.h Interface /* * Methods: getX, getY * Usage: int x = pt.getX(); * int y = pt.getY(); * ------------------------- * These methods returns the x and y coordinates of the point. */ int getX(); int getY(); * Method: toString * Usage: string str = pt.toString(); * ---------------------------------- * Returns a string representation of the Point in the form "(x,y)". std::string toString(); /* * Constructor: Point * Usage: Point origin; * Point pt(xc, yc); * ------------------------ * Creates a Point object. The default constructor sets the * coordinates to 0; the second form sets the coordinates to * xc and yc. */ Point(); Point(int xc, int yc);

The point.h Interface private: int x; /* The x-coordinate */ int y; /* The y-coordinate */ }; /* * Operator: << * Usage: cout << pt; * ------------------ * Overloads the << operator so that it is able to display Point * values. */ std::ostream & operator<<(std::ostream & os, Point pt); #endif /* * Methods: getX, getY * Usage: int x = pt.getX(); * int y = pt.getY(); * ------------------------- * These methods returns the x and y coordinates of the point. */ int getX(); int getY(); * Method: toString * Usage: string str = pt.toString(); * ---------------------------------- * Returns a string representation of the Point in the form "(x,y)". std::string toString();

The point.cpp Implementation /* * File: point.cpp * --------------- * This file implements the point.h interface. */ #include <string> #include "point.h" #include "strlib.h" using namespace std; /* Constructors */ Point::Point() { x = 0; y = 0; } Point::Point(int xc, int yc) { x = xc; y = yc;

The point.cpp Implementation /* Getters */ int Point::getX() { return x; } int Point::getY() { return y; /* The toString method and the << operator */ string Point::toString() { return "(" + integerToString(x) + "," + integerToString(y) + ")"; ostream & operator<<(ostream & os, Point pt) { return os << pt.toString(); /* * File: point.cpp * --------------- * This file implements the point.h interface. */ #include <string> #include "point.h" #include "strlib.h" using namespace std; /* Constructors */ Point::Point() { x = 0; y = 0; } Point::Point(int xc, int yc) { x = xc; y = yc;

Methods in the TokenScanner Class scanner.setInput(str) or scanner.setInput(infile) Sets the input for this scanner to the specified string or input stream. scanner.hasMoreTokens() Returns true if more tokens exist, and false at the end of the token stream. scanner.nextToken() Returns the next token from the token stream, and "" at the end. scanner.saveToken(token) Saves token so that it will be read again on the next call to nextToken. scanner.ignoreWhitespace() Tells the scanner to ignore whitespace characters. scanner.scanNumbers() Tells the scanner to treat numbers as single tokens. scanner.scanStrings() Tells the scanner to treat quoted strings as single tokens.

The End