Utilities (Part 2) Implementing static features 1.

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

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.
Written by: Dr. JJ Shepherd
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
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.
Utilities (Part 3) Implementing static features 1.
Road Map Introduction to object oriented programming. Classes
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Classes with multiple methods Part 1. Review of classes & objects Early on, we learned that objects are the basic working units in object-oriented programs.
1 Fall 2007ACS-1903 Chapter 6: Classes Classes and Objects Instance Fields and Methods Constructors Overloading of Methods and Constructors Scope of Instance.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals; Apply data abstraction.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Testing 1. Testing  testing code is a vital part of the development process  the goal of testing is to find defects in your code  Program.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
Utilities (Part 2) Implementing static features 1.
ECE122 Feb. 22, Any question on Vehicle sample code?
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo CET 3640 © Copyright by Pearson Education, Inc. All Rights Reserved.
Objects and Classes Mostafa Abdallah
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1  lecture slides online
Puzzle 1  what does the following program print? public class Puzzle01 { public static void main(String[] args) { System.out.print("C" + "S" + "E"); System.out.println('1'
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Non-static classes 1.  a utility class has features (fields and methods) that are all static  all features belong to the class  therefore, you do not.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Chapter 6 - More About Problem Domain Classes1 Chapter 6 More About Problem Domain Classes.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Classes - Intermediate
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Java: Base Types All information has a type or class designation
Topic: Classes and Objects
Java: Base Types All information has a type or class designation
Road Map Introduction to object oriented programming. Classes
CMSC 202 Static Methods.
Advanced Object Oriented Programming
Chapter 3 Introduction to Classes, Objects Methods and Strings
Classes & Objects: Examples
Building Java Programs
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Implementing Non-Static Features
Chapter 4 Writing Classes.
Advanced Object Oriented Programming
Programs and Classes A program is made up from classes
Object Oriented Programming in java
Classes, Objects and Methods
Building Java Programs
Corresponds with Chapter 5
Presentation transcript:

Utilities (Part 2) Implementing static features 1

Goals for Today 2  learn about preventing class instantiation  learn about methods  static methods  method header  method signature  method return type  method parameters  pass-by-value

new Yahtzee Objects 3  our Yahtzee API does not expose a constructor  but Yahtzee y = new Yahtzee(); is legal  if you do not define any constructors, Java will generate a default no-argument constructor for you  e.g., we get the public constructor public Yahtzee() { } even though we did not implement it

 our Yahtzee API exposes only static constants (and methods later on)  its state is constant  there is no benefit in instantiating a Yahtzee object  a client can access the constants (and methods) without creating a Yahtzee object boolean hasTriple = Yahtzee.isThreeOfAKind(dice);  can prevent instantiation by declaring a private constructor Preventing Instantiation 4

5 import java.util.Collections; import java.util.ArrayList; import java.util.List; public class Yahtzee { private Yahtzee() { // private and empty by design } public static final int NUMBER_OF_DICE = 5; }

6 import java.util.Collections; import java.util.ArrayList; import java.util.List; public class Yahtzee { private Yahtzee() { // throwing an exception prevents accidental instantiation throw new AssertionError(); } public static final int NUMBER_OF_DICE = 5; }

private 7  private fields, constructors, and methods cannot be accessed by clients  they are not part of the class API  private fields, constructors, and methods are accessible only inside the scope of the class  a class with only private constructors indicates to clients that they cannot use new to create instances of the class

Methods 8  a method performs some sort of computation  in the previous lecture, we studied how to determine if a list of 5 dice represented a roll of 3-of-a-kind: // dice is a List reference Collections.sort(dice); boolean isThreeOfAKind = dice.get(0).getValue() == dice.get(2).getValue() || dice.get(1).getValue() == dice.get(3).getValue() || dice.get(2).getValue() == dice.get(4).getValue();  we can encapsulate this computation as a method in our utility class

9 import java.util.Collections; import java.util.ArrayList; import java.util.List; public class Yahtzee { private Yahtzee() { // private and empty by design } public static final int NUMBER_OF_DICE = 5; public static boolean isThreeOfAKind(List dice) { List copy = new ArrayList (dice); Collections.sort(copy); boolean result = copy.get(0).getValue() == copy.get(2).getValue() || copy.get(1).getValue() == copy.get(3).getValue() || copy.get(2).getValue() == copy.get(4).getValue(); return result; } Why make a copy? Because we shouldn't change the client's dice.

Method header  the first line of a method declaration is sometimes called the method header public static boolean isThreeOfAKind(List dice) 10 modifiersreturn type nameparameter list

Method signature  every method has a signature  the signature consists of the method name and the types in the parameter list  our method public static boolean isThreeOfAKind(List dice) has the following signature isThreeOfAKind(List ) 11 namenumber and types of parameters signature

Method signature  other examples from java.lang.String  headers  String toUpperCase()  char charAt(int index)  int indexOf(String str, int fromIndex)  void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)  signatures  toUpperCase()  charAt(int)  indexOf(String, int)  getChars(int, int, char[], int) 12

Method Signatures  method signatures in a class must be unique  what happens if we try to introduce a second method public static boolean isThreeOfAKind(Collection dice) ?  what about public static boolean isThreeOfAKind(List dice) ? 13

Method return types  all Java methods return nothing ( void ) or a single type of value  our method public static boolean isThreeOfAKind(List dice) has the return type boolean 14

Method return values  if the method header says that a type is returned, then the method must return a value having the advertised type back to the client  you use the keyword return to return the value back to the client 15

16 import java.util.Collections; import java.util.ArrayList; import java.util.List; public class Yahtzee { private Yahtzee() { // private and empty by design } public static final int NUMBER_OF_DICE = 5; public static boolean isThreeOfAKind(List dice) { List copy = new ArrayList (dice); Collections.sort(copy); boolean result = copy.get(0).getValue() == copy.get(2).getValue() || copy.get(1).getValue() == copy.get(3).getValue() || copy.get(2).getValue() == copy.get(4).getValue(); return result; } Return the value of result back to the client.

Method return values  a method stops running immediately after a return statement is run  this means that you are not allowed to have additional code after a return statement 17

Method parameters 18  sometimes called formal parameters  parameters are the variables that appear in the parameter list  our method public static boolean isThreeOfAKind(List dice) has the parameter dice

Method parameters 19  for a method, the parameter names must be unique  but a parameter can have the same name as a field (see [notes 1.3.3])  the scope of a parameter is the body of the method  you can use the parameter just like you would any other variable inside the body of the method  the parameter does not exist outside of the method body

20 import java.util.Collections; import java.util.ArrayList; import java.util.List; public class Yahtzee { private Yahtzee() { // private and empty by design } public static final int NUMBER_OF_DICE = 5; public static boolean isThreeOfAKind(List dice) { List copy = new ArrayList (dice); Collections.sort(copy); boolean result = copy.get(0).getValue() == copy.get(2).getValue() || copy.get(1).getValue() == copy.get(3).getValue() || copy.get(2).getValue() == copy.get(4).getValue(); return result; } Use the parameter dice to make a copy.

static Methods 21  a method that is static is a per-class member  client does not need an object to invoke the method  client uses the class name to access the method boolean hasTriple = Yahtzee.isThreeOfAKind(dice);  static methods are also called class methods  a static method can only use static fields of the class [notes 1.2.4], [AJ ]

Invoking Methods 22  a client invokes a method by passing arguments to the method  the types of the arguments must be compatible with the types of parameters in the method signature  the values of the arguments must satisfy the preconditions of the method contract [JBA 2.3.3] List dice = new ArrayList (); for (int i = 0; i < 5; i++) { dice.add(new Die()); } boolean hasTriple = Yahtzee.isThreeOfAKind(dice); argument

Pass-by-value  Java uses pass-by-value to:  transfer the value of the arguments to the method  transfer the return value back to the client  consider the following utility class and its client… 23

24 import type.lib.Fraction; public class Doubler { private Doubler() { } // tries to double x public static void twice(int x) { x = 2 * x; } // tries to double f public static void twice(Fraction f) { long numerator = f.getNumerator(); f.setNumerator( 2 * numerator ); }

25 import type.lib.Fraction; public class TestDoubler { public static void main(String[] args) { int a = 1; Doubler.twice(a); Fraction b = new Fraction(1, 2); Doubler.twice(b); System.out.println(a); System.out.println(b); }

Pass-by-value  what is the output of the client program?  try it and see  an invoked method runs in its own area of memory that contains storage for its parameters  each parameter is initialized with the value of its corresponding argument 26

Pass-by-value with Reference Types 27 Fraction b = new Fraction(1, 2); 64 client b 500 Fraction object numer1 denom2 500 value of b is a reference to the new Fraction object value of b is not the Fraction 1/2

Pass-by-value with Reference Types 28 Fraction b = new Fraction(1, 2); Doubler.twice(b); 64 client b 500 Fraction object numer1 denom2 600 Doubler.twice f parameter f is an independent copy of the value of argument b (a reference) the value of b is passed to the method Doubler.twice

Pass-by-value with Reference Types 29 Fraction b = new Fraction(1, 2); Doubler.twice(b); 64 client b 500 Fraction object numer1 2 denom2 600 Doubler.twice f multiplies the numerator of the Fraction object by 2

Pass-by-value with Primitive Types 30 int a = 1; 64 client a 1 value of a is the integer value that we stored

Pass-by-value with Primitive Types 31 int a = 1; Doubler.twice(a); 64 client a 800 Doubler.twice x1 1 parameter x is an independent copy of the value of argument a (a primitive) the value of a is passed to the method Doubler.twice this is a different Doubler.twice method than the previous example (now resides at address 800 )

Pass-by-value with Reference Types 32 int a = 1; Doubler.twice(a); 64 client a 800 Doubler.twice x multiplies the value of x by 2 ; that's it, nothing else happens

Pass-by-value 33  Java uses pass-by-value for all types (primitive and reference)  an argument of primitive type cannot be changed by a method  an argument of reference type can have its state changed by a method  pass-by-value is used to return a value from a method back to the client