DESIGNING CLASSES. SPECIFICATIONS FOR THE CAR CLASS Professional programmers carefully design the classes they need before any coding is done. With well-

Slides:



Advertisements
Similar presentations
Functions Function: The strength of C language is to define and use function. The strength of C language is that C function are easy to define and use.
Advertisements

CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Animation Mrs. C. Furman. Animation  We can animate our crab by switching the image between two pictures.  crab.png and crab2.png.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming The software development method algorithms.
CS 201 Functions Debzani Deb.
Information Hiding and Encapsulation
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 7: Methods.
Moving To Code 3 More on the Problem-Solving Process §The final step in the problem-solving process is to evaluate and modify (if necessary) the program.
1 Interactive Applications (CLI) Interactive Applications Command Line Interfaces Project 1: Calculating BMI Example: Factoring the Solution Reading for.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
1 Understanding Inheritance COSC 156 C++ Programming Lecture 8.
Programming.
PROGRAMMING IN VISUAL BASIC.NET VISUAL BASIC BUILDING BLOCKS Bilal Munir Mughal 1 Chapter-5.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
CSC 212 – Data Structures Lecture 12: Java Review.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
4.1 Instance Variables, Constructors, and Methods.
Introduction to the “this” reserved word Java - Supplemented Learning By: Keenan Ratushniak.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Testing and Debugging Version 1.0. All kinds of things can go wrong when you are developing a program. The compiler discovers syntax errors in your code.
Conditional Execution
SE: CHAPTER 7 Writing The Program
CS 320 Assignment 1 Rewriting the MISC Osystem class to support loading machine language programs at addresses other than 0 1.
CPS120: Introduction to Computer Science Decision Making in Programs.
WDMD 170 – UW Stevens Point 1 WDMD 170 Internet Languages eLesson: Variables, Functions and Events (there is an audio component to this eLesson) © Dr.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Object-Oriented Programming •Object-Oriented Programming (OOP) allows you to create your program based upon modeling objects.  Your program’s properties.
“Education is a Treasure that follows you everywhere.” – Chines Proverb Methods and Functions.
Copyright © Curt Hill The IF Revisited If part 4 Style and Testing.
Object Oriented Programing (OOP)
CIS 234: Java Methods Dr. Ralph D. Westfall April, 2010.
Decisions in Python Boolean functions. A Boolean function This is a function which returns a bool result (True or False). The function can certainly work.
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.
1 Project 2: Using Variables and Expressions. 222 Project 2 Overview For this project you will work with three programs Circle Paint Ideal_Weight What.
Intro to Loops 1.General Knowledge 2.Two Types of Loops 3.The WHILE loop 1.
MIT-AITI: Functions Defining and Invoking Functions Functions as Data Function Scope: The call Object Function Arguments: The arguments objects Function.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Chapter 1: Preliminaries Lecture # 2. Chapter 1: Preliminaries Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CUSTOM OOP. SYNTAX OF A CLASS DEFINITION Class definitions (descriptions) look like this: class ClassName { Descriptions of the instance variables and.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
Object Parameters. Object References as Parameters Here is an example program: class ObjectPrinter{ public print(st:String ):void { Alert.show("Value.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Namespaces, Scopes, Access privileges
User-Defined Functions
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Understanding Inheritance
Conditions and Ifs BIS1523 – Lecture 8.
Lesson 16: Functions with Return Values
CS139 October 11, 2004.
Loop Strategies Repetition Playbook.
Workshop for Programming And Systems Management Teachers
Chapter 9 Inheritance.
Introduction to Object-Oriented Programming
design OO words Debug Variables Data types
Review of Previous Lesson
Visibilities and Static-ness
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

DESIGNING CLASSES

SPECIFICATIONS FOR THE CAR CLASS Professional programmers carefully design the classes they need before any coding is done. With well- designed classes programming is much easier and the program has fewer bugs. Object oriented design consists of deciding what classes are needed, what data they will hold, and how they will behave. All these decisions are documented (written up) and then examined. If something doesn't look right, it is fixed before any programming is done. Let us do that with our Car class.

Car A class that calculates miles per gallon. Variables Number startMiles; // Starting odometer reading Number endMiles; // Ending odometer reading Number gallons; // Gallons of gas used between the readings Constructors Car(Number startOdo, Number endingOdo, Number gallons ) Creates a new instance of a Car object with the starting and ending odometer readings and the number of gallons of gas consumed. Methods Number calculateMPG() calculates and returns the miles per gallon for the car.

PROGRAM TO USE THE CAR CLASS var line:String; var startMiles, endMiles:Number; var gallons:Number; Alert.show("Enter first reading:" ); line = txtFirstReading.text; startMiles = Number ( line ); Alert.show("Enter second reading:" ); line = txtSecondReading.text; endMiles = Number ( line ); Alert.show("Enter gallons:" ); line = txtGallons.text; gallons = Number ( line ); var car:Car = new Car( startMiles, endMiles, gallons ); Alert.show( "Miles per gallon is " + car.calculateMPG() ); Of course, the program still cannot be run because the class Car has not yet been defined.

FILLING IN THE DEFINITION class Car{ // instance variables var startMiles:Number; // Stating odometer reading var endMiles:Number; // Ending odometer reading var gallons:Number; // Gallons of gas used between the readings // constructor function Car( first:Number, last:Number, gals:Number) { startMiles = first ; endMiles = last ; gallons = gals ; } // methods function calculateMPG():Number { return (endMiles - startMiles)/gallons ; }

USING THE CLASS var car:Car = new Car( 32456, 32810, 10.6 ); Alert.show( "Miles per gallon is " + car.calculateMPG() );

POSSIBLE ERRORS class Car{ // instance variables var startMiles:Number; // Stating odometer reading var endMiles:Number; // Ending odometer reading var gallons:Number; // Gallons of gas used between the readings // constructor function Car( first:Number:Number, last:Number, gals:Number) { startMiles = first ; endMiles = last ; gallons = gals ; } // methods function calculateMPG():Number { return (last - first)/gals ; }

ANSWER the calculateMPG() method can not even see the parameters of the constructor. Another way of saying this is that the scope of the parameters is limited to the body of the method. The compiler will complain that first, last, and gals are "undefined variables" because they are used outside of their scope.

FILL IN THE BLANKS Design of the Telescope Class. The three most important numbers describing a telescope are: the diameter of the main lens (the one in front), the focal length of the main lens, and the focal length of the eyepiece. From these values other characteristics of the telescope such as its magnification and the f- number of the main lens are calculated. Rewrite (especially where there are blanks) the code in the following design for the class: class Telescope A class that models a field telescope. Constructors Telescope (diameter:Number, mainFocal:Number, eyepieceFocal:Number ) Methods // calculate the magnification of the telescope double var mag:Number = mainFocal / eyepieceFocal; // calculate the f-number of the telescope double var fN:Number = mainFocal / diameter;

Checking the Design. To check the design, write a small program that uses the class to see if it works well. Write a program that creates a Telescope object with a main lens that has a diameter of 3.0 inches, a focal length of 6.5 inches, and an eyepiece focal length of 0.8 inches. Write out its magnification and f-number. var tele:Telescope = new Telescope(3.0, 6.5, 0.8) ; Alert.show( "Power: " + tele.mag+ " F-number: " + tele.fN);

Skeleton of the Class. Fill in the blanks that give the over-all design of the class. class Telescope{ // main diameter // main focal length // eyepiece focal length }

. Fill in Instance Variables. Fill in the data type of each instance variable. class Telescope{ // Instance Variables var diameter:Number; var mainLength:Number; var eyeLength:Number; // Constructors // Methods }

Complete the Constructor. The constructor will initialize the instance variables of the object being constructed. class Telescope{ // Instance Variables var diameter: Number; var mainLength: Number; var eyeLength: Number; // Constructors public function Telescope (diameter: Number, mainLength: Number, eyeLength: Number ) { this.diameter = diameter ; this.mainLength = mainLength ; this.eyeLength = eyeLength ; } // Methods } When an instance variable and a parameter use the same identifier, you specify the instance variable of the object by saying "this.identifier" as in the above.

Complete a Method. The documentation for the magnification() method says it looks like this: // calculate the magnification of the telescope double magnification() The formula to use is: magnification = mainLength/eyeLength class Telescope{ // Instance Variables var diameter: Number; var mainLength: Number; var eyeLength: Number; // Constructors function Telescope (diameter: Number, mainLength: Number, eyeLength: Number ) { this.diameter = diameter ; this.mainLength = mainLength ; this.eyeLength = eyeLength ; } // Methods function magnification():Number { return mainLength / _____________ ; } }

Complete the other Method. The documentation for the says it looks like this: // calculate the magnification of the telescope double fNumber() The formula to use is: fNumber = mainLength/diameter class Telescope{ // Instance Variables var diameter: Number; var mainLength: Number; var eyeLength: Number; // Constructors function Telescope (diameter: Number, mainLength:Number, eyeLength: Number ) { this.diameter = diameter ; this.mainLength = mainLength ; this.eyeLength = eyeLength ; } // Methods function magnification():Number { return mainLength / eyeLength ; } function fNumber():Number { return mainLength / diameter; } }

Programming Exercises Modify the Car class by adding two methods: boolean gasHog() evaluates to true if the miles per gallon is lower than boolean economyCar() evaluates to true if the miles per gallon is higher than The constructor and the calculateMPG() method remain unchanged. Each of these new methods should use the calculateMPG() to get the miles per gallon, not calculate it themselves. An if-else statement picks the correct boolean return value. You might be tempted to make one of these common design errors: Saving miles per gallon in an instance variable of the object along with startMiles, endMiles, and gallons. This almost seems logical, but is a poor design. Don't keep a permanent copy of a value that can be easily calculated from data. The reason for this is that it adds complexity to the object, but offers little advantage. Directly calculating miles per gallon inside each of the new methods. It is usually best to do a particular calculation in a method, and to use it whenever the calculation is needed. Now if there is a bug in the calculation, or the calculation must be modified, there is only one place to look. Test your program by designing a form to allow a user to enter the first and second readings along with the number of gallons. Display the answer in a label. Ex. IO Enter first reading:10000 Enter second reading:10400 Enter gallons:10 Miles per gallon: 40 Economy Car!

Change the constructor for the Car class so that it has only one parameter, the first reading of the odometer. The miles per gallon cannot yet be calculated. Now add a method to the class: function fillUp( int miles, double gallons ) This simulates filling up the tank at a gas station: miles is the current odometer reading and gallons is the number of gallons that filled the tank. Save these values in instance variables. With this information, miles per gallon can be calculated. Write the method so that it updates the instance variables each time it is called (simulating another visit to the pumps). After each call calculateMPG() will calculate the latest miles per gallon. Write a testing program that constructs a car and calls fillUp() and calculateMPG() a few times. Ex. IO New car odometer reading:00000 Filling Station Visit odometer reading gallons to fill tank 10 Miles per gallon: 35 Economy Car! Filling Station Visit odometer reading gallons to fill tank 10 Miles per gallon: 10 Gas Hog!