CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Java Basics M Taimoor Khan
Road Map Introduction to object oriented programming. Classes
Access to Names Namespaces, Scopes, Access privileges.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
Information Hiding and Encapsulation
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Understanding class definitions Looking inside classes.
CSC 142 J 1 CSC 142 Arrays [Reading: chapter 10].
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Methods Chapter 6. 2 Program Modules in Java What we call "functions" in C++ are called "methods" in Java Purpose Reuse code Modularize the program This.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
NSIT,Jetalpur CORE JAVA CONCEPTS SURABHI MISHRA (LCE)NSIT.
4.1 Instance Variables, Constructors, and Methods.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
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.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
110-G1 Motivation: Within a program, may have to perform the same computation over and over Many programs share the same computation (e.g. sorting) To.
Slide: 1 Copyright © AdaCore Subprograms Presented by Quentin Ochem university.adacore.com.
CPS120: Introduction to Computer Science Decision Making in Programs.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Session 7 Methods Strings Constructors this Inheritance.
Defining Classes I Part A. Class definitions OOP is the dominant programming methodology in use today. OOP is the dominant programming methodology in.
CSC 142 B 1 CSC 142 Java objects: a first view [Reading: chapters 1 & 2]
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
1 Methods Introduction to Methods Passing Arguments to a Method More About Local Variables Returning a Value from a Method Problem Solving with Methods.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Namespaces, Scopes, Access privileges
Methods.
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.
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.
CSC 143 Inheritance.
6 Chapter Functions.
Defining Classes and Methods
Namespaces, Scopes, Access privileges
Object based programming in Java
Java objects: a first view
Object based programming in Java
Defining Classes and Methods
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Presentation transcript:

CSC 142 D 1 CSC 142 Instance methods [Reading: chapter 4]

CSC 142 D 2 Motivation  Divide and conquer  Break up a complex task into a set of tasks.  Each simpler task is coded in a separate method.  Simplify the development of code (faster, less bugs).

CSC 142 D 3 An illustration  Drawing a mountain landscape public void drawLandscape() { drawMountainRange(); drawChalet(); drawTrees(); }  What the method does is obvious  How it does it is relegated in the methods drawMountainRange(),…

CSC 142 D 4 Defining a method  e.g., public boolean isAHoliday(Date d){/*code*/}  Inside of a class block {}  Start with the access modifier (public or private)  Follow with the type of the method  e.g. if the method returns an int, write int for the type of the method  Follow with the method name  first word: lowercase, others: capitalize the 1 st letter.  Follow with the list of formal parameters inside ()  The method code is written between { and }

CSC 142 D 5 Access modifier: public  The method is part of the class interface  Anyone using the class can access the method // file MyClass.java public class MyClass{ public void sayHello() { System.out.println("Hello");} // constructor and other methods... } // for any user of MyClass MyClass mc = new MyClass(); mc.sayHello(); //OK, sayHello is public

CSC 142 D 6 Access modifier: private  The method is part of the class implementation  The method can only be accessed within the class // file MyClass.java public class MyClass{ private void sayHello(){ System.out.println("Hello"); } public void saySomething(){ sayHello(); // OK } } // file OtherClass.java public class OtherClass{ public void doSomething(){ MyClass mc = new MyClass(); mc.sayHello(); //Oups! Doesn’t compile } }

CSC 142 D 7 void return value  If the method doesn't send back a result, use void as the type of the method public void printWelcome() { System.out.println( "Welcome to Java!"); return; // optional statement }

CSC 142 D 8 Returning a value  The method sends 'something' back to whoever called it. That 'something' (=a result in some form) has a type. The type must appear next to the method name, e.g. public boolean isZero(int val) { // is val 0? if (val==0) return true; else return false; } The method is of type boolean since it returns a boolean (true or false).

CSC 142 D 9 Formal and actual parameters  Store in the formal parameters the input values sent to the method, e.g. in class Output: public void printInfo(String name, int age) { System.out.println("My name is " + name + ". I am "+age+" years old."); } formal parameters actual parameters  actual parameters: what is sent to the method Output output = new Output(); output.printInfo("Sandra",26); //prints My name is Sandra. I am 26 years old.  If no input, write methodName()

CSC 142 D 10 Rule for calling a method (1)  Actual and formal parameters must match  in number  in type  in order //OK output.printInfo("Sandra",26); //Oups! wrong order output.printInfo(26,"Sandra"); // Boom! wrong number output.printInfo(26); // No way! 26.5 is not an int output.printInfo("Sandra",26.5);

CSC 142 D 11 Rule for calling a method (2)  Actual and formal parameters don't have to match by name, e.g. // In the Output class public void printInfo(String name,int age) { System.out.println("My name is " + name + ". I am "+age+" years old."); } // in some other method in some other class String someName = "David"; int someAge = 11; Output output = new Output(); output.printInfo(someName,someAge); // OK

CSC 142 D 12 Control flow (1) public class CalendarUtil { public boolean isLeapYear(int year) { /*code*/ } /* constructor and other methods... */} public class MyClass{ private CalendarUtil cu = new CalendarUtil(); public void checkBirthYear(int birthYear){ if (cu.isLeapYear(birthYear)) System.out.println("Born on a leap year"); } }  What happens when checkBirthYear(1988) is executed?

CSC 142 D 13 Control flow (2)  Execute checkBirthYear(1988)  initialize birthYear to 1988  evaluate the condition in if statement: need to call the instance method isLeapYear of cu, with an actual parameter equal to 1988  Leave checkBirthYear, start executing isLeapYear  initialize year to 1988  execute the code in isLeapYear: should return true  Leave isLeapYear with the value true. Resume execution in checkBirthYear.  The if condition is true: print "Born on a leap year"

CSC 142 D 14 Control flow (3)  Inside a method, code is executed top down, statement by statement, unless  another method is called: move the control flow to that method  a return statement is encountered: move the control flow to the caller of the method (if non void return, send back a value as well).  an if statement is encountered: skip statements in if block (false condition) or, if there is an else, in else block (true condition)  a loop is encountered: repeat some statements several times (see later).

CSC 142 D 15 pre and post conditions  Document the methods. One approach: use  preconditions: what must be true to call the method  postconditions: what is true when done executing the method  e.g. to describe boolean isLeapYear(int year) /* precondition: year > =1752 (when the gregorian calendar was adopted in England) */ /* postcondition: result==(year is a leap year) */  Could have used javadoc comments /** and */

CSC 142 D 16 Defining variables (1)  As an instance field: within a class outside any method. The field is visible throughout the class and beyond if declared public.  As a local variable: within a method. public int foo(double x) { int i; // some more code } x and i can be used only between { and } defining foo. x and i are local to foo.

CSC 142 D 17 Defining variables (2)  What is the difference between x and i?  x is a formal parameter. It is automatically initialized when foo is called. It receives the value of the actual parameter, e.g. int someInt = foo(3.2); // in foo, for this call x is 3.2  i is not automatically initialized. In Java, a local variable used without having been initialized generates a compilation error. public int foo(double x) { int i; if (x > 10.) return i; /* error: What is i ? */ else return –i; /* error: What is i ? */ }

CSC 142 D 18 Local variable scope  Where the variable is visible (in other words where it can be used)  A local variable is only visible within the block where it is declared. public void foo() { int i=2; { // inner bloc i=3; //OK String s = "abc"; //OK } // end inner block s="def"; //error! s visible only in inner block }

CSC 142 D 19 Variable lifetime  Local variable (within a method)  Created when the declaration line is executed.  Destroyed when exiting the block where the variable was declared (the memory used by the variable is reclaimed). If it is a reference, is the object garbage collected? No, if there is another reference to the object. Yes, if there is no other reference of the object.  Instance variable  Created when the object is constructed  Destroyed when the object is destroyed

CSC 142 D 20 this keyword (1)  An instance method of a class is always called using an instance of the class, e.g. window.add(circle);  The instance object is not part of the actual parameter list. However, it is still passed to the method implicitly.  It can't appear in the formal parameter list  To refer to the object used to make the call, use the keyword this.

CSC 142 D 21 Using this: an example (1)  In an instance method, access the object implicitly passed to that method with the this keyword. public class SomeClass{ private int var; public void changeVar(int n){ this.var = n;/*OK, but superfluous*/} }  Could also do public void changeVar(int var) {this.var=var;} var is local to changeVar. Since the name is the same as the instance variable var, we need to use this to refer to the instance variable var (potentially confusing). The local variable shadows the instance variable.

CSC 142 D 22 Using this: an example (2)  In an instance method, any reference to an instance field or any call to another instance method done without an explicit reference uses the implicit object. public class Bar{ public void foo1(){/*code*/} public void foo2() { foo1(); // call the instance method foo1 // of the implicit object. // same as this.foo1(); } }

CSC 142 D 23 Using this: another example  Consider a Clock class to model a clock. Clock has a method tick to add 1 second to the time. Clock clock = new Clock(); //0h0mn0s clock.tick(); // 0h0mn1s  What if we want to write clock.tick().tick(); // add 2 seconds  Define tick as public Clock tick() { /* code to add one second to the current time... */ return this; }

CSC 142 D 24 Program organization  Define the classes: one java file per class  For each class, define the instance fields and methods.  Inside of each method, define local variables as needed.  What about import?  used to access libraries organized in packages.  can also define our own packages when defining new classes. Not needed for simple programs.  In practice, classes that are defined within the same folder can access one another without using any import.