Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.

Slides:



Advertisements
Similar presentations
Parameter passing mechanism: pass-by-reference. The Pass-by-reference mechanism - the agreement Recall: Parameter passing mechanism = agreement between.
Advertisements

What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Object Reference. Variables: Class Type vs. Primitive Type What does a variable hold? –primitive type value of the variable –class type memory address.
Chapter 7: User-Defined Functions II
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
The Fundamental Rule for Testing Methods Every method should be tested in a program in which every other method in the testing program has already been.
1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Classes, Objects, and Methods.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
Road Map Introduction to object oriented programming. Classes
Chapter 41 Defining Classes and Methods Chapter 4.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Classes, Objects, and Methods
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
CS180 Chapter 4 2/1/08. Announcements Project 3 is out –2 weeks due to the exam Exam –Thursday, February 7, 8:30 – 9:30 pm, WTHR 104 –Covers chapters.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Copywrite 2003 Walter Savitch These slides are for the exclusive use of students in CSE 11 at UCSD, Winter quarter They may not be copied or used.
Intro to CS – Honors I Classes and Methods GEORGIOS PORTOKALIDIS
COMP More About Classes Yi Hong May 22, 2015.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Defining Classes and Methods Chapter 4. Objectives become familiar with the concept of –a class –an object that instantiates the class learn how to –define.
Classes, Objects, and Methods
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
COMP 150: Introduction to Object-Oriented Programming Lecturer: Dr. AJ Bieszczad 4-1 Chapter 4 l Class and Method Definitions l Information Hiding and.
Introduction To Scientific Programming Chapter 4 – Defining Classes and Methods.
Defining Classes and Methods Chapter 4. Object-Oriented Programming Our world consists of objects (people, trees, cars, cities, airline reservations,
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Class and Method Definitions. UML Class Diagram Automobile - fuel: double - speed: double - license: String + increaseSpeed(double howHardPress): void.
Peyman Dodangeh Sharif University of Technology Spring 2014.
1 Week 8 l Methods l Parameter passing Methods. 2 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call.
Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapters 4 and 5: Excerpts l Class and Method Definitions l Information.
Chapter 5Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 5 l Programming with Methods l Polymorphism l Constructors.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Methods.
CPSC 233 Tutorial 5 February 9 th /10 th, Java Classes Each Java class contains a set of instance variables and methods Instance Variables: Type.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Defining Classes and Methods
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
3 Introduction to Classes and Objects.
Chapter 3: Using Methods, Classes, and Objects
Static and non-Static Chapter 5.
Outline Class and Method Definitions
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Classes and Methods
Corresponds with Chapter 7
Classes, Objects, and Methods
Defining Classes and Methods
Object Oriented Programming in java
Java Programming Language
Defining Classes and Methods
Defining Classes and Methods
More About Objects and Methods Chapter 5 Programming with Methods
Presentation transcript:

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 4 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference l Parameter passing Defining Classes and Methods

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 2 Announcements/Reminders l Exam 1 »Thursday, February 10, 7-8pm, MTHW 210 »Chapters 1-4 »20 MC questions (2 points each) »4 programming questions (15 pts each) »If you have a conflict, contact KC VanZandt ASAP. »Old exam(s) posted on website soon l Project 1 Grades released on WebCT: for regrade check test cases, then l Project 3 released: due Thursday, Feb. 17 at 10:30 pm. (2 weeks b/c of test)

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 3 Last Week’s Quiz What will be the output of the following program: int a = 5; if ( a-- > 4 || a++ < 0 ) { System.out.println(a); }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 4 Last Week’s Quiz (cont) lore 35 % more Quiz2.java public class Quiz2 { public static void main(String[] args) { int a=5; if ( a-- > 4 || a++ < 0 ) { System.out.println(a); } lore 36 % javac Quiz2.java lore 37 % java Quiz2 4

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 5 Instantiating (Creating) Objects l Syntax: className instanceName = new className(); Note the keyword new For example, the text defines a class named SpeciesFirstTry //instantiate an object of this class SpeciesFirstTry speciesOfTheMonth = new SpeciesFirstTry(); l Public instance variables can be accessed using the dot operator: speciesOfTheMonth.name = “Klingon ox”;

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 6 Instantiating (Creating) Objects Can also do: SpeciesFirstTry speciesOfTheMonth;... speciesOfTheMonth = new SpeciesFirstTry(); We will see what each of these does later…

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 7 Using Methods l Methods are actions that an object can perform. l To use a method you invoke or call it. Example of a method call: speciesOfTheMonth.writeOutput() l Two basic kinds of methods: »methods that return a single value »void methods that do some action other than returning a value calling object— tells which object will do the action method name—tells which action the object will perform parameter list in parentheses—parameters give info to the method, but in this example there are no parameters

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 8 Return Type of Methods l All methods require that the return type be specified l Return types may be: »a primitive data type, such as char, int, double, etc. »a class, such as String, SpeciesFirstTry, etc. »void if no value is returned You can use a method any place where it is legal to use its return type, for example the readLineInt() method of SavitchIn returns an integer, so this is legal: int next = SavitchIn.readLineInt();

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 9 Return Statement Methods that return a value must execute a return statement that includes the value to return l For example: public int getCount() { int count; // count is the number of … … return count; }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 10 void Method Example The definition of the writeOutput method of SpeciesFirstTry : Assuming instance variables name, population, and growthRate have been defined and assigned values, this method performs an action (writes values to the screen) but does not return a value public void writeOutput() { System.out.println("Name = " + name); System.out.println("Population = " + population); System.out.println("Growth = " + growthRate + "%"); }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 11 Return Statement in void method void methods can use a return, but must not return anything l For example: public void writeOutput() { System.out.println("Name = " + name);... return; }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 12 When and Where to Declare Variables Good programming Practice: l declare variables at the beginning of the method l initialize variables when you declare them l do not declare variables inside loops it is ok to declare loop counters in the Initialization field of for loops, e.g. for(int i=0; i <10; i++)… »But we prefer: int i=0;... for(i=0; i <10; i++)…

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 13 Passing Values to a Method: Parameters l Some methods can be more flexible (therefore useful) if we pass them input values l Input values for methods are called passed values or parameters l Parameters and their data types must be specified inside the parentheses of the heading in the method definition »these are called formal parameters l The calling object must put values of the same data type, in the same order, inside the parentheses of the method invocation »these are called arguments, or actual parameters

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 14 Parameter Passing Example l What is the formal parameter in the method definition? »numberIn l What is the argument in the method invocation? »next //Definition of method to double an integer public int doubleValue(int numberIn) { return 2 * numberIn; } //Invocation of the method... somewhere in main int next = SavitchIn.readLineInt(); System.out.println("Twice next = " + doubleValue(next));

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 15 Pass-By-Value: Primitive Data Types as Parameters l When the method is called, the value of each argument is copied (assigned) to its corresponding formal parameter l The number of arguments must be the same as the number of formal parameters l The data types of the arguments must be the same as the formal parameters and in the same order l Formal parameters are initialized to the values passed l Formal parameters are local to their method l Variables used as arguments cannot be changed by the method »the method only gets a copy of the variable's value

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 16 Variables: Class Type vs. Primitive Type What does a variable hold? »It depends on the type of type, primitive type or class type l A primitive type variable holds the value of the variable l Class types are more complicated »they have methods and instance variables l A class type variable holds the memory address of the object »the variable does not actually hold the value of the object »in fact, as stated above, objects generally do not have a single value and they also have methods, so it does not make sense to talk about its "value"

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 17 Instantiating (Creating) Objects l Species elephant; elephant - creates storage location for memory address (pointer) l elephant = new Species(); - allocates memory to store data objects of class name growthRate population

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 18 Instantiating (Creating) Objects name growthRate population elephant

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 19 Assignment with Variables of a Class Type klingon = new Species(); earth = new Species();... klingon.set(“Klingon ox”, 10, 15); earth.set(“Black rhino”, 11, 2); earth = klingon; earth.set(“Elephant”, 100, 12); System.out.println(“earth:”); earth.writeOutput(); System.out.println(“klingon:”); klingon.writeOutput(); What will the output be? (see the next slide)

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 20 Assignment with Variables of a Class Type klingon.set(“Klingon ox”, 10, 15); earth.set(“Black rhino”, 11, 2); earth = klingon; earth.set(“Elephant”, 100, 12); System.out.println(“earth:”); earth.writeOutput(); System.out.println(“klingon:”); klingon.writeOutput(); earth: Name = Elephant Population = 100 Growth Rate = 12% klingon: Name = Elephant Population = 100 Growth Rate = 12% Output: What will the output be? klingon and earth both print Elephant. Why do they print the same thing? (see the next slide)

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 21 Assignment with Variables of a Class Type klingon.set(“Klingon ox”, 10, 15); earth.set(“Black rhino”, 11, 2); earth = klingon; earth.set(“Elephant”, 100, 12); System.out.println(“earth:”); earth.writeOutput(); System.out.println(“klingon:”); klingon.writeOutput(); Why do they print the same thing? The assignment statement makes earth and klingon refer to the same object. When earth is changed to “ Elephant ”, klingon is changed also. earth klingon Black rhino 11 2 Klingon ox Before the assignment statement, earth and klingon refer to two different objects. earth klingon Klingon ox After the assignment statement, earth and klingon refer to the same object.

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 22 Gotcha: Comparing Class Variables l A class variable returns a number, but it is not its value l It returns the memory address where the object with that variable name is stored If two class variables are compared using ==, it is the addresses, not the values that are compared! This is rarely what you want to do! Use the class's equals() method to compare the values of class variables

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 23 Example: Comparing Class Variables Use equals method (not the double-equals sign) to compare values //User enters first string String firstLine = SavitchIn.readLine(); //User enters second string String secondLine = SavitchIn.readLine(); if(firstLine == secondLine) //this compares their addresses { } if(firstLine.equals(secondLine)) //this compares their values { }

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 24 Pass the Address: Class Types as Method Parameters l In the same way, class variable names used as parameters in a method call copy the argument's address (not the value) to the formal parameter l So the formal parameter name also contains the address of the argument l It is as if the formal parameter name is an alias for the argument name Any action taken on the formal parameter is actually taken on the original argument! l Unlike the situation with primitive types, the original argument is not protected for class types!

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 25 Example: Class Type as a Method Parameter The method call makes otherObject an alias for s2, therefore the method acts on s2, the DemoSpecies object passed to the method! l This is unlike primitive types, where the passed variable cannot be changed. //Method definition with a DemoSpecies class parameter public void makeEqual(DemoSpecies otherObject) { otherObject.name = this.name; otherObject.population = this.population; otherObject.growthRate = this.growthRate; } //Method invocation DemoSpecies s1 = new DemoSpecies("Crepek", 10, 20); DemoSpecies s2 = new DemoSpecies(); s1.makeEqual(s2);

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 26 Summary Part 1 l Classes have instance variables to store data and methods to perform actions l Declare instance variables to be private so they can be accessed only within the same class There are two kinds of methods: those that return a value and void -methods l Methods can have parameters of both primitive type and class type

Chapter 4Java: an Introduction to Computer Science & Programming - Walter Savitch 27 Summary Part 2 l Parameters of a primitive type work differently than those of a class type »primitive type parameters are call-by-value, so the calling object's variable is protected within the called method (the called method cannot change it) »class type parameters pass the address of the calling object so it is unprotected (the called method can change it) l For similar reasons, the operators = and == do not behave the same for class types as they do for primitive types (they operate on the address of object and not its values) Therefor you should usually define an equals method for classes you define (to allow the values of objects to be compared)