1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.

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

Interfaces A Java interface is a collection
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Java Software Solutions
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. 2 Objects  An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it)  For.
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.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes The programs we’ve written in previous examples have.
Writing Classes in Java
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.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
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 Third Edition by John Lewis and William Loftus.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
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.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved2/48 Writing Classes We've been using predefined classes. Now we will learn.
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.
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.
Chapter 6 Object-Oriented Design. © 2004 Pearson Addison-Wesley. All rights reserved6-2 Object-Oriented Design Now we can extend our discussion of the.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© 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.
Wednesday –POD –I have updated grades in powerschool. If you have a zero for a lab grade, it probably means you didn’t DropItToMe. Please do so. –Slides.
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
© 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. 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.
© 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.
Writing Classes We've been using predefined classes from the Java API. Now we will learn to write our own classes. Chapter 4 focuses on: class definitions.
Anatomy of a Class & Method
Classes A class is a blueprint of an object
Chapter 4: Writing Classes
Chapter 5 – Writing Classes
Encapsulation & Visibility Modifiers
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
Classes, Encapsulation, Methods and Constructors (Continued)
Anatomy of a Method.
Writing Classes.
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:

1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing method overloading method decomposition

2 Objects  An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it)  For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails"  The state of the coin is its current face (heads or tails)  The behavior of the coin is that it can be flipped  Note that the behavior of the coin might change its state

3 Classes  A class is a blueprint of an object  It is the model or pattern from which objects are created  For example, the String class is used to define String objects  Each String object contains specific characters (its state)  Each String object can perform services (behaviors) such as toUpperCase  The String class was provided for us by the Java standard class library  But we can also write our own classes that define specific objects that we need

Classes  A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations

The Coin Class  In our Coin class we could define the following data: face, an integer that represents the current face HEADS and TAILS, integer constants that represent the two possible states  We might also define the following methods: a Coin constructor, to initialize the object a flip method, to flip the coin a isHeads method, to determine if the current face is heads a toString method, to return a string description for printing

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

Data Scope  The scope of data is the area in a program in which that data can be used (referenced)  Data declared at the class level can be used by all methods in that class  Data declared within a method can be used only in that method  Data declared within a method is called local data

Instance Data  The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own  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  The objects of a class share the method definitions, but each has its own data space  That's the only way two objects can have different states

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

UML Diagrams  UML stands for the Unified Modeling Language  UML diagrams show relationships among classes and objects  A UML class diagram consists of one or more classes, each with sections for the class name, attributes, and methods  Lines between classes represent associations  Associations can show multiplicity

UML Class Diagrams  A UML class diagram for the FlipRace program: FlipRace main (args : String[]) : void Coin face : int flip() : void isHeads() : boolean toString() : String 12

UML Diagrams  A UML object diagram consists of one or more instantiated objects.  It is a snapshot of the objects during an executing program, showing data values coin1 : Coin face = 0 coin2 : Coin face = 1

13 Encapsulation  We can take one of two views of an object: internal - the variables the object holds and the methods that make the object useful external - the services that an object provides and how the object interacts  From the external view, an object is an encapsulated entity, providing a set of specific services  These services define the interface to the object  Recall from Chapter 2 that an object is an abstraction, hiding details from the rest of the system

14 Encapsulation  An object should be self-governing  Any changes to the object's state (its variables) should be made only by that object's methods  We should make it difficult, if not impossible, to access an object’s variables other than via its methods  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

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

16 Visibility Modifiers  In Java, we accomplish encapsulation through the appropriate use of visibility modifiers  A modifier is a Java reserved word that specifies particular characteristics of a method or data value  We've used the modifier final to define a constant  Java has three visibility modifiers: public, protected, and private  The protected modifier involves inheritance, which we will discuss later

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

18 Visibility Modifiers  Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients  Public methods are also called service methods  A method created simply to assist a service method is called a support method  Since a support method is not intended to be called by a client, it should not be declared with public visibility

Visibility Modifiers publicprivate Variables Methods Violate encapsulation Enforce encapsulation Provide services to clients Support other methods in the class

Driver Programs  A driver progam drives the use of other, more interesting parts of a program  Driver programs are often used to test other parts of the software  The Banking class contains a main method that drives the use of the Account class, exercising its services  See Banking.java (page 226)Banking.java  See Account.java (page 227)Account.java

See Banking.java (page 226) Banking.java // Banking.java to exercise the use of multiple Account objects. public class Banking { public static void main (String[] args) { Account acct1 = new Account ("Ted Murphy", 72354, ); Account acct2 = new Account ("Jane Smith", 69713, 40.00); Account acct3 = new Account ("Edward Demsey", 93757, ); acct1.deposit (25.85); double smithBalance = acct2.deposit (500.00); System.out.println ("Smith balance after deposit: " + smithBalance); System.out.println ("Smith balance after withdrawal: " + acct2.withdraw (430.75, 1.50)); acct3.withdraw (800.00, 0.0); // exceeds balance acct1.addInterest(); acct2.addInterest(); acct3.addInterest(); System.out.println (); System.out.println (acct1); System.out.println (acct2); System.out.println (acct3); }}

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

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

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

Method Header  A method declaration begins with a method header char calc (int num1, int num2, String message) method name return type 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

Method Body  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; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing

27 The return Statement  The return type of a method indicates the type of value that the method sends back to the calling location  A method that does not return a value has a void return type  A return statement specifies the value that will be returned return expression;  Its expression must conform to the return type

Parameters  Each time a method is called, the actual parameters in the invocation are copied into the formal parameters 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");

Local Data  Local variables can be declared inside a method  The formal parameters of a method create automatic local variables when the method is invoked  When the method finishes, all local variables are destroyed (including the formal parameters)  Keep in mind that instance variables, declared at the class level, exists as long as the object exists  Any method in the class can refer to instance data

30 Constructors Revisited  Recall that a constructor is a special method that is used to initialize a newly created object  When writing a constructor, remember that: it has the same name as the class it does not return a value it has no return type, not even void it typically sets the initial values of instance variables  The programmer does not have to define a constructor for a class

31 Overloading Methods  Method overloading is the process of using the same method name for multiple methods  The signature of each overloaded method must be unique  The signature includes the number, type, and order of the parameters  The compiler determines which version of the method is being invoked by analyzing the parameters  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

33 Overloaded Methods  The println method is overloaded: println (String s) println (int i) println (double d) and so on...  The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

34 Overloading Methods  Constructors can be overloaded  Overloaded constructors provide multiple ways to initialize a new object  See SnakeEyes.java (page 236)SnakeEyes.java  See Die.java (page 237)Die.java

Method Decomposition  A method should be relatively small, so that it can be understood as a single entity  A potentially large method should be decomposed into several smaller methods as needed for clarity  A service method of an object may call one or more support methods to accomplish its goal  Support methods could call other support methods if appropriate

Pig Latin  The process of translating an English sentence into Pig Latin can be decomposed into the process of translating each word  The process of translating a word can be decomposed into the process of translating words that begin with vowels begin with consonant blends (sh, cr, tw, etc.) begins with single consonants  See PigLatin.java (page 238)PigLatin.java  See PigLatinTranslator.java (page 240)PigLatinTranslator.java

Class Diagrams Revisited  In a UML class diagram, public members can be preceded by a plus sign  Private members are preceded by a minus sign  A class diagram for the PigTranslator program: PigLatin + main (args : String[]) : void + translate (sentence : String) : String - translateWord (word : String) : String - beginsWithVowel (word : String) : boolean - beginsWithBlend (word : String) : boolean 11 PigLatinTranslator

Object Relationships  Objects can have various types of relationships to each other  A general association, as we've seen in UML diagrams, is sometimes referred to as a use relationship  A general association indicates that one object (or class) uses or refers to another object (or class) in some way  We could even annotate an association line in a UML diagram to indicate the nature of the relationship Author Book writes

Object Relationships  Some use associations occur between objects of the same class  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  See RationalNumbers.java (page 244)RationalNumbers.java  See Rational.java (page 246)Rational.java

Aggregation  An aggregate object is an object that contains references to other objects  For example, an Account object contains a reference to a String object (the owner's name)  An aggregate object represents a has-a relationship  A bank account has a name  Likewise, a student may have one or more addresses  See StudentBody.java (page 250)StudentBody.java  See Student.java (page 252)Student.java  See Address.java (page 253)Address.java

Aggregation in UML  An aggregation association is shown in a UML class diagram using an open diamond at the aggregate end StudentBody + main (args : String[]) : void + toString() : String 12 Student - firstName : String - lastName : String - homeAddress : Address - schoolAddress : Address + toString() : String - streetAddress : String - city : String - state : String - zipCode : long Address

Summary  Chapter 4 has focused on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing method overloading method decomposition