©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 4 - 1 Chapter 4 Defining Your Own Classes Part 1 Animated Version.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Advertisements

© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 4: Writing Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1 Animated.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
Classes, Encapsulation, Methods and Constructors
Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Introduction to methods Chapter 5: Classes and Objects in Depth.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
Chapter Chapter 4 Defining Your Own Classes Part 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
Develop Instantiable classes (continue). Exam 1 – section 02 Avg = 131 (87%). Max: 148.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Why Programmer-Defined Classes Using just the String,
Defining Your Own Classes Part 3. class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor)
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
© 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)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 4 Defining Your Own Classes Part 1 Animated Version.
BCS 2143 Object Oriented Programming Defining Your Own Classes (Part 1)
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
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.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:
DCS 2133 Object Oriented Programming Defining Your Own Classes Part 2.
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.
Classes and Objects. Object Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
1 Classes, Encapsulation, Methods and Constructors Class definitions Scope of Data –Instance data –Local data The this Reference Encapsulation and Java.
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.
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.
Classes and Objects. Object vs. Class Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2  A class could be considered as a set of objects having.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Dr. Majed Abdouli © Objects and Classes 1 Dr. Majed Abdouli © 2015, adapted from Liang, Introduction to Java Programming, Eighth Edition, (c) 2011.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 4 : Defining Your Own Classes Part 1 - Objectives After you have read and studied this chapter, you should be able to Define a class with multiple.
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.
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.
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
Defining Your Own Classes
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Anatomy of a Method.
Writing Classes.
Chapter 4 Writing Classes.
Chapter 5: Classes and Objects in Depth
Outline Anatomy of a Class Encapsulation Anatomy of a Method
Presentation transcript:

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 4 Defining Your Own Classes Part 1 Animated Version

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Objectives After you have read and studied this chapter, you should be able to Define a class with multiple methods and data members Differentiate the local and instance variables Define and use value-returning methods Distinguish private and public methods Distinguish private and public data members Pass both primitive data and objects to a method

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Why Programmer-Defined Classes Using just the String, GregorianCalendar, JFrame and other standard classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. Learning how to define our own classes is the first step toward mastering the skills necessary in building large programs. Classes we define ourselves are called programmer- defined classes.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter First Example: Using the Bicycle Class class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setOwnerName("Ben Jones"); owner1 = bike1.getOwnerName( ); //Output the information owner2 = bike2.getOwnerName( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The Definition of the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public void Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Multiple Instances Once the Bicycle class is defined, we can create multiple instances. Bicycle bike1, bike2; bike1bike2 : Bicycle ownerName : Bicycle ownerName “Adam Smith” “Ben Jones” bike1 = new Bicycle( ); bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); bike2.setOwnerName("Ben Jones"); Sample Code

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The Program Structure and Source Files BicycleRegistrationBicycle There are two source files. Each class definition is stored in a separate file. BicycleRegistration.javaBicycle.java To run the program: 1. javac Bicycle.java (compile) 2. javac BicycleRegistration.java (compile) 3. java BicycleRegistration (run)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Class Diagram for Bicycle Method Listing We list the name and the data type of an argument passed to the method. Method Listing We list the name and the data type of an argument passed to the method. Bicycle setOwnerName(String) Bicycle( ) getOwnerName( )

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Data Member Declaration ; private String ownerName ; Modifiers Data Type Name Note: There’s only one modifier in this example.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Data Scope The scope of data is the area in a program in which that data can be referenced (used) Data declared at the class level can be referenced 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Method Declaration ( ){ } public void setOwnerName ( String name ) { ownerName = name; } Statements Modifier Return Type Method Name Parameter

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Method Declaration ( ){ } public String getOwnerName ( ) { return ownerNam; } Statements Modifier Return Type Method Name Parameter A value-returning method must include a return statement.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Accessor and Mutator A method that returns information about an object (such as who is the owner of an a bicycle) is called as accessor. –E.g., the method getOwnerName() A method that sets a property of an object is called a mutator. –E.g.; the method setOwnerName(…)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Constructor A constructor is a special method that is executed when a new instance of the class is created. public ( ){ } public Bicycle ( ) { ownerName = "Unassigned"; } Statements Modifier Class Name Parameter

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Constructor If a class constructor is not declared, a default constructor is supplied by the compiler that accepts no parameters: modifier ClassName() { } A constructor has no return type specified in the method header, not even void A common error is to put a return type on a constructor, which makes it a “regular” method that happens to have the same name as the class it is possible to define more than one constructor to a class. Multiple constructor are called Overloaded constructor

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter UML Class Diagrams A UML class diagram for the BicycleRegistration program: BicycleRegistration main (args : String[]) : void Bicycle ownerName : String getOwnerName () : String setOwnerName(String value) : void

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Compiling and Running Bicycle Use the name of the main class to refer the whole program. To run the bicycleRegistration program must follow these steps: 1.Compile the Bicycle class Javac Bicycle.java 2.Compile the BicycleRegistration class. Javac BicycleRegistration.java 3.Run the BicycleRegistration class Java BicycleRegistration.java To manage a program that includes multiple programmer-defined classes, save the source files in the same folder.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Second Example: Using Bicycle and Account class SecondMain { //This sample program uses both the Bicycle and Account classes public static void main(String[] args) { Bicycle bike; Account acct; String myName = "Jon Java"; bike = new Bicycle( ); bike.setOwnerName(myName); acct = new Account( ); acct.setOwnerName(myName); acct.setInitialBalance(250.00); acct.add(25.00); acct.deduct(50); //Output some information System.out.println(bike.getOwnerName() + " owns a bicycle and"); System.out.println("has $ " + acct.getCurrentBalance() + " left in the bank"); }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The Account Class class Account { private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public double getCurrentBalance( ) { return balance; } public String getOwnerName( ) { return ownerName; } public void setInitialBalance (double bal) { balance = bal; } public void setOwnerName (String name) { ownerName = name; } Page 1Page 2

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter The Program Structure for SecondMain SecondMainBicycle SecondMain.javaBicycle.java To run the program: 1. javac Bicycle.java (compile) 2. javac Account.java (compile) 2. javac SecondMain.java (compile) 3. java SecondMain (run) Account.java Account Note: You only need to compile the class once. Recompile only when you made changes in the code.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Arguments and Parameters An argument is a value we pass to a method class Account {... public void add(double amt) { balance = balance + amt; }... } class Sample { public static void main(String[] arg) { Account acct = new Account();... acct.add(400);... }... } argument parameter A parameter is a placeholder in the called method to hold the value of the passed argument.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Matching Arguments and Parameters The number or arguments and the parameters must be the same class Demo { public void compute(int i, int j, double x) {... } Demo demo = new Demo( ); int i = 5; int k = 14; demo.compute(i, k, 20); 3 arguments 3 parameters The matched pair must be assignment- compatible (e.g. you cannot pass a double argument to a int parameter) Arguments and parameters are paired left to right Passing Side Receiving Side

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Memory Allocation Separate memory space is allocated for the receiving method. Passing Side i5 k Receiving Side i j x Values of arguments are passed into memory allocated for parameters. Literal constant has no name

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Passing Objects to a Method As we can pass int and double values, we can also pass an object to a method. When we pass an object, we are actually passing the reference (name) of an object –it means a duplicate of an object is NOT created in the called method

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Passing a Student Object class LibraryCard { private Student owner; public void setOwner(Student st) { owner = st; } LibraryCard card2; card2 = new LibraryCard(); card2.setOwner(student); Passing Side Receiving Side : LibraryCard owner borrowCnt 0 : Student name “Jon Java” student card2 st 1 1 Argument is passed Value is assigned to the data member 2 State of Memory

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sharing an Object We pass the same Student object to card1 and card2 Since we are actually passing a reference to the same object, it results in owner of two LibraryCard objects pointing to the same Student object

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Encapsulation We can take one of two views of an object: –internal - the details of the variables and methods of the class that defines it –external - the services that an object provides and how the object interacts with the rest of the system

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Encapsulation Methods variable Client An encapsulated object can be thought of as a black box -- its inner workings are hidden from the client The client invokes the interface methods of the object, which manages the instance variable

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Information Hiding and Visibility Modifiers The modifiers public and private designate the accessibility of data members and methods. If a class component (data member or method) is declared private, client classes cannot access it. If a class component is declared public, client classes can access it. Internal details of a class are declared private and hidden from the clients. This is information hiding. This feature is called Encapsulation

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Accessibility Example class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientService

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Data Members Should Be private Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private. Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods. In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Guideline for Visibility Modifiers Guidelines in determining the visibility of data members and methods: –Declare instance variables private. –Declare instance methods private if they are used only by the other methods in the same class. –Declare the class constants public if you want to make their values directly readable by the client programs. If the class constants are used for internal purposes only, then declare them private.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Diagram Notation for Visibility public – plus symbol (+) private – minus symbol (-)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Visibility Modifiers publicprivate Variables Methods Provide services to clients Support other methods in the class Enforce encapsulation Violate encapsulation

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Class Constants A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence The compiler will issue an error if you try to change the value of a constant Remember, the use of constants –provides a meaningful description of what the values stand for. number = UNDEFINED; is more meaningful than number = -1; –provides easier program maintenance. We only need to change the value in the constant declaration instead of locating all occurrences of the same value in the program code

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter A Sample Use of Constants class Dice { private static final int MAX_NUMBER = 6; private static final int MIN_NUMBER = 1; private static final int NO_NUMBER = 0; private int number; public Dice( ) { number = NO_NUMBER; } //Rolls the dice public void roll( ) { number = (int) (Math.random() * (MAX_NUMBER - MIN_NUMBER + 1) + MIN_NUMBER); } //Returns the number on this dice public int getNumber( ) { return number; } Exercise Die1

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Variable Scope The scope of variable is the area in a program in which that variable can be referenced (used) Global Variable: –variable declared at the class level can be referenced by all methods in that class Local Variable : –variable declared within a method –can be used only in that method class { //global variable //can’t use local variable } Method { //local variable // can use global variable }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Local Variables Local variables are declared within a method declaration and used for temporary services, such as storing intermediate computation results. public double convert(int num) { double result; result = Math.sqrt(num * num); return result; } local variable

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Local, Parameter & Data Member An identifier appearing inside a method can be a local variable, a parameter, or a data member. The rules are –If there’s a matching local variable declaration or a parameter, then the identifier refers to the local variable or the parameter. –Otherwise, if there’s a matching data member declaration, then the identifier refers to the data member. –Otherwise, it is an error because there’s no matching declaration.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Sample Matching class MusicCD { private String artist; private String title; private String id; public MusicCD(String name1, String name2) { String ident; artist = name1; title = name2; ident = artist.substring(0,2) + "-" + title.substring(0,9); id = ident; }... }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Calling Methods of the Same Class So far, we have been calling a method of another class (object). It is possible to call method of a class from another method of the same class. –in this case, we simply refer to a method without dot notation

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter doIt helpMe helpMe(); obj.doIt(); main Method Control Flow The called method is often part of another class or object

The toString Method All classes that represent objects should define a toString method The toString method returns: – a String that represents the object in some way ( the programmer declare it ) It is called automatically when – an object is concatenated to a string, –or when it is passed to the println method