Chapter 7: Programming with methods and classes..

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

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.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
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.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
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.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BPJ444: Business Programming Using Java Classes and Objects Tim McKenna
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.
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
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.
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.
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
1 Programming with methods and classes. 2 Methods  Instance (or member) method Operates on a object (i.e., and instance of the class) String s = new.
CSC 142 Computer Science II Zhen Jiang West Chester University
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Programming with methods and classes. Methods  Instance method Operates on a object (i.e., and instance of the class) String s = new String("Help every.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter 3 Objects and Classes. Objects Object – a data type with structure, state, and operations to access and manipulate state - an instance of a class.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
CSI 3125, Preliminaries, page 1 Overloading Methods In Java it is possible to define two or more methods within the same class that share the same name,
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Classes, Interfaces and Packages
Programming with methods and classes Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
1 Programming with methods and classes Chapter 7 Fall 2006 CS 101 Aaron Bloomfield.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
1 Programming with methods and classes Chapter 7 Fall 2005 CS 101 Aaron Bloomfield.
(C) 2010 Pearson Education, Inc. All rights reserved.  Best way to develop and maintain a large program is to construct it from small, simple pieces,
1 Programming with methods and classes Chapter 7 Spring 2006 CS 101 Aaron Bloomfield.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Arrays Chapter 7.
Topic: Classes and Objects
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Namespaces, Scopes, Access privileges
Chapter 6 Methods: A Deeper Look
Programming with methods and classes
Chapter 9 Inheritance and Polymorphism
Programming with methods and classes
Group Status Project Status.
Java Classes and Objects 3rd Lecture
Classes, Objects and Methods
Review for Midterm 3.
Presentation transcript:

Chapter 7: Programming with methods and classes.

Methods  Instance method Operates on a object (i.e., an instance of the class) String s = new String(“Always be prepared for class"); int n = s.length();  Class method Service provided by a class and it is not associated with a particular object String t = String.valueOf(n); Instance method Class method 6/8/20162AP Central 2010/11

Data fields  Instance variable and instance constants Attribute of a particular object Usually a variable Point p = new Point(5, 5); int px = p.x;  Class variable and constants Collective information that is not specific to individual objects of the class Usually is constant Color favoriteColor = Color.MAGENTA; double favoriteNumber = Math.PI - Math.E; Instance variable Class constants 6/8/20163AP Central 2010/11

The following table shows the access to members permitted by each modifier. Access Levels Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N The first data column indicates whether the class itself has access to the member defined by the access level. The second column indicates whether classes in the same package as the class have access to the member. The third column indicates whether subclasses of the class — declared outside this package — have access to the member. The fourth column indicates whether all classes have access to the member. 6/8/20164AP Central 2010/11

Consider – Conversion.java  Supports conversion between English and metric values based on: d degrees Fahrenheit = (d – 32)/1.8 degrees Celsius 1 mile = kilometers 1 gallon = liters 1 ounce = grams 1 acre = square miles 6/8/20165AP Central 2010/11

Conversion Implementation public class Conversion { // conversion equivalencies private static final double KILOMETERS_PER_MILE = ; private static final double LITERS_PER_GALLON = ; private static final double GRAMS_PER_OUNCE = ; private static final double SQMILES_PER_ACRE = ; 6/8/20166AP Central 2010/11

Conversion Implementation // temperature conversions methods public static double fahrenheitToCelsius(double f) { return (f - 32) / 1.8; } public static double celsiusToFahrenheit(double c) { return 1.8 * c + 32; } // length conversions methods public static double kilometersToMiles(double km) { return km / KILOMETERS_PER_MILE; } 6/8/20167AP Central 2010/11

Conversion implementation 6/8/20168AP Central 2010/11

Conversion Implementation // mass conversions methods public static double litersToGallons(double liters) { return liters / LITERS_PER_GALLON; } public static double gallonsToLiters(double gallons) { return gallons * LITERS_PER_GALLON; } public static double gramsToOunces(double grams) { return grams / GRAMS_PER_OUNCE; } public static double ouncesToGrams(double ounces) { return ounces * GRAMS_PER_OUNCE; } 6/8/20169AP Central 2010/11

Conversion Implementation // area conversions methods public static double sqmilesToAcres(double sqmiles) { return sqmiles / SQMILES_PER_ACRE; } public static double acresTosqmiles(double acres) { return acres * SQMILES_PER_ACRE; } 6/8/201610AP Central 2010/11

Conversion use System.out.print("Enter a length in kilometers: "); double kilometers = Keyboard.readDouble(); System.out.print("Enter a mass in liters: "); double liters = Keyboard.readDouble(); System.out.print("Enter a mass in grams: "); double grams = Keyboard.readDouble(); System.out.print("Enter an area in hectares: "); double sqmiles = Keyboard.readDouble(); double miles = Conversion.kilometersToMiles(kilometers); double gallons = Conversion.litersToGallons(liters); double ounces = Conversion.gramsToOunces(grams); double acres = Conversion.sqmilesToAcres(sqmiles); 6/8/201611AP Central 2010/11

A Conversion use System.out.println(kilometers + " kilometers = " + miles + " miles "); System.out.println(liters + " liters = " + gallons + " gallons"); System.out.println(grams + " grams = " + ounces + " ounces"); System.out.println(sqmiles + " sqmiles = " + acres + " acres"); 2.0 kilometers = miles 3.0 liters = gallons 4.0 grams = ounces 5.0 sqmiles = acres 6/8/201612AP Central 2010/11

A preferred Conversion use NumberFormat style = NumberFormat.getNumberInstance(); style.setMaximumFractionDigits(2); style.setMinimumFractionDigits(2); System.out.println(kilometers + " kilometers = " + style.format(miles) + " miles "); System.out.println(liters + " liters = " + style.format(gallons) + " gallons"); System.out.println(grams + " grams = " + style.format(ounces) + " ounces"); System.out.println(hectares + " hectares = " + style.format(acres) + " acres"); 2.0 kilometers = 1.24 miles 3.0 liters = 0.79 gallons 4.0 grams = 0.14 ounces 5.0 sqmilres = acres Part of java.text 6/8/ AP Central 2010/11

Method invocations  Actual parameters provide information that is otherwise unavailable to a method  When a method is invoked Java sets aside memory for that particular invocation  Called the activation record Activation record stores, among other things, the values of the formal parameters Formal parameters initialized with values of the actual parameters  After initialization, the actual parameters and formal parameters are independent of each other Flow of control is transferred temporarily to that method 6/8/201614AP Central 2010/11

Value parameter passing demonstration public class Demo { public static double add(double x, double y) { double result = x + y; return result; } public static double multiply(double x, double y) { x = x * y; return x; } public static void main(String[] args) { double a = 8, b = 11; double sum = add(a, b); System.out.println(a + " + " + b + " = " + sum); double product = multiply(a, b); System.out.println(a + " * " + b + " = " + product); } 6/8/201615AP Central 2010/11

Value parameter passing demonstration multiply() does not change the actual parameter a 6/8/201616AP Central 2010/11

Demo.java walkthrough 6/8/201617AP Central 2010/11

Demo.java walkthrough 6/8/201618AP Central 2010/11

PassingReferences.java public class PassingReferences { public static void f(Point v) { v = new Point(0, 0); } public static void g(Point v) { v.setLocation(0, 0); } public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); System.out.println(p); g(p); System.out.println(p); } 6/8/201619AP Central 2010/11

PassingReferences.java run g() can change the attributes of the object to which p refers 6/8/201620AP Central 2010/11

PassingReferences.java public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); java.awt.Point[x=10,y=10 ] 6/8/201621AP Central 2010/11

PassingReferences.java public static void f(Point v) { v = new Point(0, 0); } 6/8/201622AP Central 2010/11

PassingReferences.java public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); System.out.println(p); g(p); java.awt.Point[x=10,y=10 ] 6/8/201623AP Central 2010/11

PassingReferences.java public static void g(Point v) { v.setLocation(0, 0); } 6/8/201624AP Central 2010/11

PassingReferences.java public static void main(String[] args) { Point p = new Point(10, 10); System.out.println(p); f(p); System.out.println(p); g(p); System.out.println(p); java.awt.Point[x=10,y=10 ] java.awt.Point[x=0,y=0] 6/8/201625AP Central 2010/11

Task – Triple.java  Represent objects with three integer attributes  public Triple() Constructs a default Triple value representing three zeros  public Triple(int a, int b, int c) Constructs a representation of the values a, b, and c  public int getValue(int i) Returns the i-th element of the associated Triple  public void setValue(int i, int value) Sets the i-th element of the associated Triple to value 6/8/201626AP Central 2010/11

Task – Triple.java  Represent objects with three integer attributes  public String toString() Returns a textual representation of the associated Triple  public Object clone() Returns a new Triple whose representation is the same as the associated Triple  public boolean equals(Object v) Returns whether v is equivalent to the associated Triple These three methods are overrides of inherited methods 6/8/201627AP Central 2010/11

Triple.java implementation 6/8/201628AP Central 2010/11

Triple.java implementation // Triple(): specific constructor public Triple(int a, int b, int c) { setValue(1, a); setValue(2, b); setValue(3, c); } // Triple(): specific constructor - alternative definition public Triple(int a, int b, int c) { this.setValue(1, a); this.setValue(2, b); this.setValue(3, c); } 6/8/201629AP Central 2010/11

Triple.java implementation  Class Triple like every other Java class Automatically an extension of the standard class Object Class Object specifies some basic behaviors common to all objects  These behaviors are said to be inherited Three of the inherited Object methods  toString()  clone()  equals() 6/8/201630AP Central 2010/11

Recommendation  Classes should override (i.e., provide a class-specific implementation)  toString()  clone()  equals()  By doing so, the programmer-expected behavior can be provided System.out.println(p); // displays string version of // object referenced by p System.out.println(q); // displays string version of // object referenced by q 6/8/201631AP Central 2010/11

Triple.java toString() implementation public String toString() { int a = getValue(1); int b = getValue(2); int c = getValue(3); return "Triple[" + a + ", " + b + ", " + c+ "]"); }  Consider Triple t1 = new Triple(10, 20, 30); System.out.println(t1); Triple t2 = new Triple(8, 88, 888); System.out.println(t2);  Produces Triple[10, 20, 30] Triple[8, 88, 888] 6/8/201632AP Central 2010/11

Triple.java clone() implementation public String clone() { int a = getValue(1); int b = getValue(2); int c = getValue(3); return new Triple(a, b, c); }  Consider Triple t1 = new Triple(9, 28, 29); Triple t2 = (Triple) t1.clone(); System.out.println("t1 = " + t1); System.out.println("t2 = " + t2);  Produces Triple[9, 28, 29] Must cast! 6/8/201633AP Central 2010/11

Triple.java equals() implementation public boolean equals(Object v) { if (v instanceof Triple) { int a1 = getValue(1); int b1 = getValue(2); int c1 = getValue(3); Triple t = (Triple) v; int a2 = t.getValue(1); int b2 = t.getValue(2); int c2 = t.getValue(3); return (a1 == a2) && (b1 == b2) && (c1 == c2); } else { return false; } Can’t be equal unless it’s a Triple Compare corresponding attributes 6/8/201634AP Central 2010/11

Triple.java equals() Triple e = new Triple(4, 6, 10); Triple f = new Triple(4, 6, 11);, Triple g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boolean flag1 = e.equals(f); 6/8/201635AP Central 2010/11

Triple.java equals() Triple e = new Triple(4, 6, 10); Triple f = new Triple(4, 6, 11);, Triple g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boolean flag2 = e.equals(g); 6/8/201636AP Central 2010/11

Triple.java equals() Triple e = new Triple(4, 6, 10); Triple f = new Triple(4, 6, 11);, Triple g = new Triple(4, 6, 10); Triple h = new Triple(4, 5, 11); boolean flag2 = g.equals(h); 6/8/201637AP Central 2010/11

What’s wrong? class Scope { public static void f(int a) { int b = 1; // local definition System.out.println(a); // print 10 a = b; // update a System.out.println(a); // print 1 } public static void main(String[] args) { int i = 10; // local definition f(i); // invoking f() with i as parameter System.out.println(a); System.out.println(b); } Variables a and b do not exist in the scope of method main() 6/8/201638AP Central 2010/11

Blocks and scope rules  A block is a list of statements nested within braces A method body is a block A block can be placed anywhere a statement would be legal  A block contained within another block is a nested block  A formal parameter is considered to be defined at the beginning of the method body  A local variable can be used only in a statement or nested blocks that occurs after its definition  An identifier name can be reused as long as the blocks containing the duplicate declarations are not nested one within the other  Name reuse within a method is permitted as long as the reuse occurs in distinct blocks 6/8/201639AP Central 2010/11

Legal class Scope2 { public static void main(String[] args) { int a = 10; f(a); System.out.println(a); } public static void f(int a) { System.out.println(a); a = 1; System.out.println(a); } 6/8/201640AP Central 2010/11

Legal but not recommended public void g() { { int j = 1; // define j System.out.println(j); // print 1 } { int j = 10; // define a different j System.out.println(j); // print 10 } { char j = // define a different j System.out.println(j); // print } 6/8/201641AP Central 2010/11

What’s the output? for (int i = 0; i < 3; ++i) { int j = 0; ++j; System.out.println(j); }  The scope of variable j is the body of the for loop j is not in scope when ++i j is not in scope when i < 3 are evaluated j is redefined and re-initialized with each loop iteration 6/8/201642AP Central 2010/11

Overloading  Have seen it often before with operators int i = ; double x = ; String s = "April " + "June";  Java also supports method overloading Several methods can have the same name Useful when we need to write methods that perform similar tasks but different parameter lists Method name can be overloaded as long as its signature is different from the other methods of its class  Difference in the names, types, number, or order of the parameters 6/8/201643AP Central 2010/11

Legal public static int min(int a, int b, int c) { return Math.min(a, Math.min(b, c)); } public static int min(int a, int b, int c, int d) { return Math.min(a, min(b, c, d)); } 6/8/201644AP Central 2010/11

Legal public static int power(int x, int n) { int result = 1; for (int i = 1; i <= n; ++i) { result *= x; } return result; } public static double power(double x, int n) { double result = 1; for (int i = 1; i <= n; ++i) { result *= x; } return result; } 6/8/201645AP Central 2010/11

What’s the output? public static void f(int a, int b) { System.out.println(a + b); } public static void f(double a, double b) { System.out.println(a - b); } public static void main(String[] args) { int i = 19; double x = 54.0; f(i, x); } 6/8/201646AP Central 2010/11