Chapter 4 Topics: class declarations method declarations

Slides:



Advertisements
Similar presentations
Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
Advertisements

Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
FIT Objectives By the end of this lecture, students should: understand the structure of a class understand the concept of a method understand.
School of Computing Science CMT1000 © Ed Currie Middlesex University Lecture 10: 1 TEST!!
COMP More About Classes Yi Hong May 22, 2015.
11 Values and References Chapter Objectives You will be able to: Describe and compare value types and reference types. Write programs that use variables.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Writing Classes (Chapter 4)
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
©Silberschatz, Korth and Sudarshan1 Methods Method Basics Parameters Void vs. Non-void Methods Recursion.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Methods We write methods in our programs for many reasons:
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
Classes - Intermediate
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Comp1004: Building Better Objects II Encapsulation and Constructors.
Comp1004: Building Better Objects I Methods. Coming up Methods and Parameters – Why Parameterise? – Call by value, call by reference Return Types – Methods.
Memory Management.
Operator Overloading Introduction
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Java Memory Management
User-Written Functions
Suppose we want to print out the word MISSISSIPPI in big letters.
Chapter 7: User-Defined Functions II
Java Memory Management
Building Java Programs
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
Programming Language Concepts (CIS 635)
Methods.
Stack Data Structure, Reverse Polish Notation, Homework 7
CS 302 Week 11 Jim Williams, PhD.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Starting Out with Java: From Control Structures through Objects
Creating Objects in a Few Simple Steps
Encapsulation and Constructors
Building Java Programs
Group Status Project Status.
Building Java Programs
CHAPTER 6 GENERAL-PURPOSE METHODS
IFS410 Advanced Analysis and Design
CS2011 Introduction to Programming I Methods (II)
Building Java Programs Chapter 2
Lecture Notes – Week 4 Chapter 5 (Loops).
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Classes, Objects and Methods
Building Java Programs
Building Java Programs Chapter 2
Building Java Programs
Names of variables, functions, classes
Building Java Programs
References Revisted (Ch 5)
Lecture 3 More on Flow Control, More on Functions,
Corresponds with Chapter 5
Building Java Programs
Chapter 4 Test Review First day
Presentation transcript:

Chapter 4 Topics: class declarations method declarations encapsulation instance variables method declarations return types parameters method overloading

The Person class, version 1 public class Person { // state // behavior public void talk() { System.out.println("blah, blah, blah, ...\n"); } public void study (String course) { System.out.println("study, study, study, ..."); System.out.println("I just love studing " + course + "!\n"); public boolean likes (String firstName) { if ( firstName.charAt( firstName.length()-1 ) == 'y' ) return true; else return false;

The Driver class, version 1 public class Driver { public static void main(String [] args) { Person student1 = new Person(); student1.talk(); student1.study("CSCI 201"); if ( student1.likes("Tommy") ) System.out.println("Student #1 likes Tommy"); else System.out.println("Student #1 does not like Tommy"); }

Person class, version 2---adding state public class Person { private int age; private String name; … public String getName() { return name; } public void setName( String newName ) { name = newName; public int getAge() { return age; public void setAge( int newAge ) { age = newAge;

Driver class, version 2 public class Driver { public static void main(String [] args) { Person student1 = new Person(); student1.setName("Sally"); student1.setAge(21); System.out.println("Student #1's name is " + student1.getName() + "\n"); System.out.println("Student #1's age is " + student1.getAge() + "\n"); student1.talk(); student1.study("CSCI 201"); if ( student1.likes("Tommy") ) System.out.println("Student #1 likes Tommy"); else System.out.println("Student #1 does not like Tommy"); }

Person class, version 3 public class Person { private int age; private String name; Person (String startingName, int startingAge) { age = startingAge; name = startingName; } Person () { age = 18; name = "Bob"; … public int getAge() { return age; public void setAge( int newAge ) { age = newAge;

Driver class, version 3 public class Driver { public static void main(String [] args) { Person student1 = new Person(); Person student2 = new Person("Tommy", 23); System.out.println("Student #1's name is " + student1.getName() ); System.out.println("Student #1's age is " + student1.getAge() ); System.out.println("Student #2's name is " + student2.getName() ); System.out.println("Student #2's age is " + student2.getAge() ); if ( student1.likes( student2.getName() ) ) System.out.println("Student #1 likes " + student2.getName() ); else System.out.println("Student #1 does not like " + student2.getName() ); }

Formal Parameters A method has a header and a body. This is the simple version of the setAge method of the Person class: public void setAge(int newAge) { age = newAge; } This method has a parameter called newAge which is an int. When this method is called, it expects to be passed an integer value. newAge is called a formal parameter. It is a placeholder for a value that will be supplied when the method is invoked. } Method header Method body Because the method may be called many times with many different values, we can't know what the value will be. So, we give a name to the value that will come along when the method is called, and write our method code in terms of this name. Switch to BlueJ and run the setAge method of the Person class. Show that BlueJ has to prompt you for the value to be passed to the method, otherwise it couldn't know what the value was supposed to be. Ask the students what will happen if you give it something of the wrong type.

Actual Arguments The method is called by addressing a Person object and asking it to invoke this method. Person friend = new Person(); friend.setAge(20); The integer value 20 is the actual argument that is given to the method when it is invoked. int myAge = 25; friend.setAge(myAge); The setAge method sees only the value 25. It does not see the name of the variable that happens to contain the value of the actual argument. Write on the OHP a few examples of other expressions being passed as actual arguments, e.g. friend.setAge(myAge + 3); friend.setAge(brother.getAge()); friend.setAge(newAge); where newAge happens to be the same name as the name of the formal parameter in the method. Ask students what will happen if you change the name of a formal parameter. Demonstrate. Mention that it's not a good idea to name the parameter the same name as an attribute that you will be referring to in the method. If you do this, you have to go to some trouble to distinguish between them. Don't go into details on this unless somebody asks.

Memory Allocation for Parameters Memory is allocated to the formal parameter at the time the method is called. The memory location is initialised to the actual argument. The memory for the formal parameter is deallocated when the method finishes executing. We call this "going out of scope". Draw a picture on the overhead showing how the memory for the parameter comes into existence at the time the method is called, and disappears again when the method terminates. There will be more on scoping later.

Methods with Multiple Parameters Suppose we had a method that could change all the attributes of a Person object. public void setAllAttributes(String aName, int anAge ) { name = aName; age = anAge; } The call to this method would have to pass two actual arguments, e.g. friend.setAllAttributes("Jack", myAge + 1); A similar method could be used in the assignment to set all the Movie attributes, say. Point out that the values passed to the method can be the results of evaluated expressions. They don't have to be just constants or variables. Give some more examples here.

Matching Formal Parameters with Actual Arguments The actual arguments passed to a method must match the formal parameters in all of the following: number type order The compiler assumes that the first actual argument matches the first formal parameter, the second actual argument matches the second formal parameter, etc. The names of formal parameters do not have to match the names of the actual arguments. The called method does not see the names, it sees only values. Show in BlueJ some examples of calls that won't work with this method, i.e. wrong number of arguments, wrong order, wrong type. Ask students to predict what will happen. Show in BlueJ how the prompts for the setAllAttributes method are in the order written into the code, and that the names and types of the formal parameters are shown also, to make sure you get it right. Show what happens when you leave the quotes off the String for name, and explain why.

Passing Multiple Values of the Same Type public double divideNumbers(int dividend, int divisor) { if (divisor != 0) return (double)dividend / divisor; return 0; } When the method is called, e.g. System.out.println(divideNumbers(12, 3)); the first parameter is taken as the dividend, and the second as the divisor. Show in BlueJ what happens if you put the parameters in the wrong order. This method is in the TestPerson class. Explain without going into detail here that it is necessary to say you want a double answer here, otherwise you get an int, because you are dividing an int by an int. We'll talk more about casting later. FINISH THE FIRST HALF OF THE LECTURE HERE.

Returning Values from Methods A value returned from a method replaces the call to the method. Person aPerson = new Person(); System.out.println(aPerson.getAge()); System.out.println(0); Show on the overhead how this is similar to an arithmetic expression evaluation. The second example is showing how the boolean value returned by the set method should be used to find out whether the change to the attribute really took place, as this may affect what happens next in the program. This was seen in the inputAge method in the week 4 lecture.

Returning Values from Methods When a method returns a value you need to use right away, or “hold on” to it to use it later. Holding on to it: Person aperson = new Person(); String goodName = aperson.getName(); if( aperson.likes(goodName) ) … else Using it right away: if( aperson.likes( aperson.getName() ) )