Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.

Slides:



Advertisements
Similar presentations
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Chapter 4: Writing Classes
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Chapter 4: Writing Classes
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter Day 7. © 2007 Pearson Addison-Wesley. All rights reserved4-2 Agenda Day 7 Questions from last Class?? Problem set 1 Corrected  Good results 3.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Foundations of Program Design Writing Classes. 2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
COMP 14: Writing Classes June 6, 2000 Nick Vallidis.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Writing Classes (Chapter 4)
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
© 2004 Pearson Addison-Wesley. All rights reserved September 12, 2007 Encapsulation ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
1 b Boolean expressions b truth tables b conditional operator b switch statement b repetition statements: whilewhile do/whiledo/while forfor Lecture 3.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes We've been using predefined classes. Now we will learn.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Chapter 4 Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Writing Classes Chapter 4.
Anatomy of a Class & Method
Classes A class is a blueprint of an object
Chapter 4: Writing Classes
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.
Chapter 5 – Writing Classes
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
CSCI 1100/1202 April 10,
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Anatomy of a Method.
Chapter 4 Writing Classes.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Encapsulation September 13, 2006 ComS 207: Programming I (in Java)
Chapter 4: Writing Classes
Presentation transcript:

Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program development

2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors - what it can do (or be done to it)behaviors - what it can do (or be done to it)  Example: String state - characters comprising the stringstate - characters comprising the string behaviors - services, such as toUpperCasebehaviors - services, such as toUpperCase b Example: coin state - "heads" or "tails”state - "heads" or "tails” behaviors - “flip” (may change its state)behaviors - “flip” (may change its state) b A class is a blueprint of an object

Classes: Create your own b A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations

Classes: Brew your own b The scope of data is the area in a program in which that data can be used (referenced) int x, y; char ch; Data declared at class level can be used by all methods in class Local data: - can only be used in these methods int x, y, z; char ch; int x, w; int z, y; char ch;

Writing Methods b A method declaration specifies the code that will be executed when the method is invoked (or called) b When a method is invoked, the flow of control jumps to the method and executes its code b When complete, the flow returns to the place where the method was called and continues b The invocation may or may not return a value, depending on how the method was defined

myMethod(); myMethodcompute Method Control Flow b The called method could be within the same class, in which case only the method name is needed

doIt helpMe helpMe(); obj.doIt(); main Method Control Flow b The called method could be part of another class or object

The Coin Class  In our Coin class we could define the following data: face, an integer that represents the current faceface, an integer that represents the current face HEADS and TAILS, integer constants that represent the two possible statesHEADS and TAILS, integer constants that represent the two possible states b We might also define the following methods: a Coin constructor, to set up the objecta Coin constructor, to set up the object a flip method, to flip the coina flip method, to flip the coin a getFace method, to return the current facea getFace method, to return the current face a toString method, to return a string for printinga toString method, to return a string for printing

The Coin Class b See CountFlips.java (page 179) CountFlips.java b See Coin.java (page 180) Coin.java  Once the Coin class has been defined, we can use it again in other programs as needed  Note that the CountFlips program did not use the toString method b A program will not necessarily use every service provided by an object

Instance Data  The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own b A class declares the type of the data, but it does not reserve any memory space for it  Every time a Coin object is created, a new face variable is created as well b The objects of a class share the method definitions, but they have unique data space b That's the only way two objects can have different states

Instance Data b See FlipRace.java (page 182) FlipRace.java face 0 coin1 int face; class Coin face 1 coin2

12 Encapsulation b You can take one of two views of an object: internal - the structure of its data, the algorithms used by its methodsinternal - the structure of its data, the algorithms used by its methods external - the interaction of the object with other objects in the programexternal - the interaction of the object with other objects in the program b From the external view, an object is an encapsulated entity, providing a set of specific services b Services define the interface to the object b Objects are thus abstractions hiding details from the rest of the systemhiding details from the rest of the system

13 Encapsulation b An object should be self-governing b Any changes to the object's state (its variables) should be accomplished by that object's methods b We should make it difficult, if not impossible, for one object to "reach in" and alter another object's state b The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

14 Encapsulation b An encapsulated object can be thought of as a black box b Its inner workings are hidden to the client, which only invokes the interface methods Client Methods Data

15 Visibility Modifiers b Members of a class that are declared with public visibility can be accessed from anywhere b Members of a class that are declared with private visibility can only be accessed from inside the class b Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package b Java modifiers are discussed in detail in Appendix F

16 Visibility Modifiers: Rules of thumb  Instance data should be private  service methods should be public  support methods should be private

Method Declarations Revisited b A method declaration begins with a method header public char calc (int num1, int num2, String message) methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument visibilitymodifier

Method Declarations b The method header is followed by the method body char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } Must be consistent with return type Must be consistent with return type A method that does not return a value has a void return type A method that does not return a value has a void return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing

Parameters b Each time a method is called, the actual arguments in the invocation are copied into the formal arguments char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc (25, count, "Hello");

20 Constructors b Constructor: special method to create and set up a new object it has the same name as the classit has the same name as the class it does not return a valueit does not return a value it has no return type, not even voidit has no return type, not even void it often sets the initial values of instance variablesit often sets the initial values of instance variables default constructor gets created if you do not define onedefault constructor gets created if you do not define one

Writing Classes b Sometimes an object has to interact with other objects of the same type  For example, we might add two Rational number objects together as follows: r3 = r1.add(r2);  One object ( r1 ) is executing the method and another ( r2 ) is passed as a parameter b See RationalNumbers.java (page 196) RationalNumbers.java b See Rational.java (page 197) Rational.java

22 Overloading Methods b Method overloading is the process of using the same method name for multiple methods b The signature of each overloaded method must be unique b The signature includes the number, type, and order of the parameters b The return type of the method is not part of the signature

Overloading Methods float tryMe (int x) { return x +.375; } Version 1 float tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32)Invocation

24 Overloaded Methods  The println method is overloaded: println (String s) println (String s) println (int i) println (int i) println (double d) println (double d) etc. etc.  The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println ("The total is:"); System.out.println (total); System.out.println (total);

25 Overloading Methods b Constructors can be overloaded b An overloaded constructor provides multiple ways to set up a new object b See SnakeEyes.java (page 203) SnakeEyes.java b See Die.java (page 204) Die.java

The StringTokenizer Class  The StringTokenizer class is defined in java.util  A StringTokenizer object separates a string into smaller substrings (tokens)  nextToken method returns the next token in the string Two constructors:  StringTokenizer (String str, String delimiters )  StringTokenizer (String str) By default, string is separated at white spaceBy default, string is separated at white space

27 Program Development b The creation of software involves four basic activities: establishing the requirementsestablishing the requirements creating a designcreating a design implementing the codeimplementing the code testing the implementationtesting the implementation b The development process is much more involved than this, but these basic steps are a good starting point

28 Requirements b Requirements specify the tasks a program must accomplish (what to do, not how to do it) b They often include a description of the user interface b An initial set of requirements are often provided, but usually must be critiqued, modified, and expanded b It is often difficult to establish detailed, unambiguous, complete requirements b Careful attention to the requirements can save significant time and money in the overall project

29 Design b An algorithm is a step-by-step process for solving a problem b A program follows one or more algorithms to accomplish its goal b The design of a program specifies the algorithms and data needed b In object-oriented development, the design establishes the classes, objects, and methods that are required b The details of a method may be expressed in pseudocode, which is code-like, but does not necessarily follow any specific syntax

Method Decomposition b A method should be relatively small, so that it can be readily understood as a single entity b A potentially large method should be decomposed into several smaller methods as needed for clarity b Therefore, a service method of an object may call one or more support methods to accomplish its goal b See PigLatin.java (page 207) PigLatin.java b See PigLatinTranslator.java (page 208) PigLatinTranslator.java PigLatinTranslator.java

31 Implementation b Implementation is the process of translating a design into source code b Most novice programmers think that writing code is the heart of software development, but it actually should be the least creative step b Almost all important decisions are made during requirements analysis and design b Implementation should focus on coding details, including style guidelines and documentation

32 Testing b A program should be executed multiple times with various input sets in an attempt to find errors b Debugging is the process of discovering the cause of a problem and fixing it b Programmers often erroneously think that there is "only one more bug" to fix b Tests should focus on design details as well as overall requirements