Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS18000: Problem Solving and Object-Oriented Programming

Similar presentations


Presentation on theme: "CS18000: Problem Solving and Object-Oriented Programming"— Presentation transcript:

1 CS18000: Problem Solving and Object-Oriented Programming
Welcome slide for display pre-bell.

2 Defining Methods Parameters Return Values
Methods and Classes Defining Methods Parameters Return Values

3 Java Class Java class includes…
Fields: attributes of an object or the class Methods: operations on an object or the class Within certain limitations: Fields are accessible to methods of the class Fields and methods may be static or non-static When static, fields and methods are “of the class” When non-static, fields and methods are “of the object”

4 Static and Non-Static Fields
One memory location shared by all objects of the class Same value shared by all methods What is this good for? Non-static field: Each instance of the class (object) has its own memory location for the field Different value (in general) in each object Draw a picture of a class box with static fields in it and several object boxes with non-static fields. Use the upcoming Counter class with static field x and non-static field y. Show a simple example with incrementing a static variable through one object and accessing it through another. Repeat with a non-static field. Answer the question: What is this good for?

5 Java Terminology: Variables
Instance variables: non-static fields in a class declaration Class variables: static fields in a class declaration Local variables: variables in method or block Parameters: variables in a method declaration Source: Write these on the board for later reference.

6 Problem: Counter Create a class with static and non-static counters
Create objects Increment the counters Print values before and after Do this in DrJava interactions pane before showing/writing the main method.

7 Solution 1: Counter public class Counter { int x; static int y; public static void main(String[] args) { Counter alice = new Counter(); Counter bob = new Counter(); alice.x = 10; alice.y = 42; bob.x = 50; bob.y = 99; System.out.println(alice.x); System.out.println(alice.y); System.out.println(bob.x); System.out.println(bob.y); alice.y++; System.out.println(alice.y); System.out.println(bob.y); bob.y++; }

8 Methods Method: a parameterized block of code that may return a value
Every method exists inside some class Useful for… Reusability: Reduce redundancy in code Readability: Identify logical operation by name (abstraction) Modularity: software developers can code and test independently Think: methods are “part of” the class Would be good to have specific examples for each of the “Useful for” items. Reusability: Only one person needs to write Math.sqrt(…) and everyone else can use it. Readability: The actions of foundWordHorizontal(…) help the reader understand what it does, without getting bogged down in the details of how it does it. Modularity: When writing large programs, it is helpful to delegate methods or entire classes to individual programmers to write, then combine the sources later for testing.

9 Basic Method Syntax return_type methodName(param_list) { statements; return_if_needed; } return_type: type of value to be returned (void if no return value) param_list: list of parameters expected by method (includes types and local name, can be empty)

10 Parameters and Arguments
Parameters allow a method to work on different data values Parameter: a variable local to a method Argument: an expression that is passed to the corresponding parameter at time of method call Argument values are copied into parameter variables Argument values to a method must match the number and types of parameters of the method int calc (double x, int y) {… return z;} sum = calc (r,s); These two terms are often used interchangeably—it is useful to maintain a distinction, at least as far as understanding goes. Draw a picture that shows a method declaration like “boolean foundWordHorizontal(String word, int startRow, int startCol)” and call ”if (foundWordHorizontal(words[i], startRow, startCol + i) { … }”. We’ll talk about overloading later, but… Java allows you to have different versions of the same method with different parameter types. It then chooses the appropriate method depending on the actual argument values being passed to the method.

11 Flow of Control for Method Calls
Before call: argument values at calling site are copied to parameter variables in called method Then… The calling method is “suspended” The called method begins at the top of the method body and runs to completion (return statement or the end) The calling method continues where it left off After call: Return value from called method becomes value returned to calling site

12 Parameters: Call by Value
Parameter variables are distinct from variables passed in as arguments void changer(int x) { x = 12; } int y = 5; changer(y); System.out.println(y); // prints 5

13 Solution 2: Counter public class Counter { int x; static int y = 42; Counter(int x) { this.x = x; } public static void main(String[] args) { Counter alice = new Counter(100); Counter jimmy = new Counter(500); System.out.printf("%s: x = %d, y = %d\n", "alice", alice.x, alice.y); System.out.printf("%s: x = %d, y = %d\n", "jimmy", jimmy.x, jimmy.y); alice.x++; alice.y++; jimmy.x++; jimmy.y++; Show this solution complete, but open it in lecture notes (Counter 2 Start folder). Refactor into Solution 3 on next slide.

14 Solution 3: Counter public class Counter { // [fields and constructor omitted] static void display(String name, Counter c) { System.out.printf("%s: x = %d, y = %d\n", name, c.x, c.y); } public static void main(String[] args) { Counter alice = new Counter(100); Counter jimmy = new Counter(500); display("alice", alice); display("jimmy", jimmy); alice.x++; alice.y++; jimmy.x++; jimmy.y++; Encourage students to play with simple programs like this to help them understand what is going on. HW17 is similar.

15 Static and Non-Static Methods
May only access static fields and call other static methods in the class Can be called using class name: Math.pow(2,5) Non-static method: May also access non-static fields associated with the particular object Must be associated with an object in some way in order to be called, e.g., t3.describe() If no object specified, “this” implied: describe() is same as this.describe() Contrast this slide with static and non-static fields from last time.

16 Extended Method Syntax
[static] return_type methodName(param_list) { statements; return_if_needed; } static: method is a static method Not static: method is an “instance method” (AKA “object method”)

17 Constructors Counter c1 = new Counter(500);
Not exactly a method, but very similar Callable using “new” operator May take parameters May access all fields of class (including static) Main task: Initialize the object being allocated Does not explicitly return a value… …but the new operator that started it returns a reference to the newly created object Reminder example for chalk board: Counter c1 = new Counter(500);

18 Scope of Variables Scope: where in the code the variable is usable
Basic rule: A variable is usable from the point of declaration to the end of the enclosing block Special cases… Parameters: accessible within the method body For loop variable: accessible within heading and body

19 Example: Scope1a public class Scope1 { int x; void one(int x) { // OK: hides field x // int x; // cannot have in same scope as parameter } void two() { int x = 10; // OK: hides field x while (true) { // int x; // error: same scope as x above Note that two-variables in same scope rule is a favorite test question among the TAs.

20 Example: Scope1b public class Scope1 { public static void main(String[] args) { { // independent block 1 int x = 12; } { // independent block 2 int x = 15; for (int i = 0; i < 10; i++) // i is available in header and body System.out.println(i); // System.out.println(i); // i is now "out of scope" A variable that is out-of-scope is another favorite exam question among the TAs.

21 Limitations Because of Scope Rules
Cannot have two variables with same name active in same scope (compiler gives a syntax error) Exception: parameters and local variables can “shadow” (hide) fields with the same name Use this.field to access hidden field You’ve seen this used in many constructors

22 Example: Scope2 public class Scope2 { int x; String name; Scope2(int x, String aName) { this.x = x; // common style to initialize a field name = aName; // alternative style that doesn't require 'this' } void doit() { int x = 10; // OK: hides field x this.x = x; // allows access to hidden field x public static void main(String[] args) { Scope2 sc1 = new Scope2(12, "Fred"); Scope2 sc2 = new Scope2(25, "Ralph");

23 What is this anyway? Java reserved word…
…cannot have a variable named “this” Used only within a non-static method or constructor It is a reference to the “current object” Used to access any field or method (member) of the current object Can also be used to access overloaded constructors, more on this later.

24 When designing a class… (1)
Non-static fields are the attributes of the objects of the class Wheel diameter Tree circumference Puzzle matrix Static fields are shared by all objects of the class Constants Totals or other variables that accumulate across all objects The Tree example is coming soon, re numberOfTrees static field.

25 When designing a class… (2)
Non-static methods operate on the attributes of the class (think: “do an action on/with object”) computeDiameter computeSolution Static methods operate on static variables or use no non-local variables at all readPuzzle, readWords, computeSqrt Utility methods: process parameters, return value main method of a program

26 Problem: Modeling Trees
Individual trees have a circumference Collectively, a number of trees (Tree objects) have been created (with new) Write the Tree class as given on the next slide.

27 Solution: Modeling Trees
public class Tree { double circumference; static int numberOfTrees = 0; Tree(double circumference) { this.circumference = circumference; numberOfTrees = numberOfTrees + 1; } double getRadius() { return circumference / (2 * Math.PI); static int getNumberOfTrees() { return numberOfTrees;

28 Problem: Making Trees Write a program to create a number of trees
Print how many trees were created Could use a counter in the method(s) that create a new Tree… … but using a Tree static variable keeps the bookkeeping centralized without having to insert the same code in all places that create a Tree Write the TreeMaker class as shown on the next slide. Or, just show it. The example is very similar to the Counter example from earlier and the Zombie example given for home work.

29 Solution: Tracking the Trees
public class TreeMaker { public static void main(String[] args) { while (Math.random() < 0.9) { Tree t = new Tree(Math.random() * 100); System.out.printf("tree has radius %.3f\n", t.getRadius()); } System.out.printf("created %d trees\n", Tree.getNumberOfTrees());

30 Methods and Classes Extent, Passing References, Overloading
Encapsulation Accessors and Mutators Where to cover Covariant return type?

31 Extent (vs. Scope) Scope: Where a variable is “visible”
Extent: How long a value is kept (its “lifetime”) Variable: lifetime same as scope When block left, value of variable is lost So, initializers are re-done on block entry while (…) { int i = 0; i++; System.out.println(i); } Object: lifetime lasts until it is no longer accessible (e.g., no variables reference it) In DrJava, show this example of class Extent.

32 Passing References by Value
Reminder: parameter passing is “by value” Passing an object reference by value means… The “value” is the reference to (address of) the object The called method cannot modify the variable where the reference is stored But, it can modify the object it references Hold on to your socks, this concept is tricky, but oh-so important!

33 Example: Reference by Value
public class Danger { static void modify(int[] a) { a[0] = -1; // modifies object referenced by x } public static void main(String[] args) { int[] x = { 42 }; System.out.println(x[0]); modify(x);

34 Example: Reference by Value (1)
public class ReferenceByValue { static void modify(int[] a) { for (int i = 0; i < a.length; i++) a[i]++; a = new int[a.length]; // has no effect on variable x in main a[i] = -1; // this array is different from the one x references } static void printArray(String message, int[] a) { System.out.printf("%s: ", message); System.out.printf("%d ", a[i]); System.out.printf("\n");

35 Example: Reference by Value (2)
public class ReferenceByValue { // [see previous slide] public static void main(String[] args) { int[] x = new int[5]; printArray("x new", x); for (int i = 0; i < x.length; i++) x[i] = i; printArray("x initialized", x); modify(x); printArray("x modified", x); }

36 Overloading Constructors and Methods (1)
Term signature refers to the name and parameter types of a method or constructor public static void main(String[] args) Each constructor and method in a class must have a unique signature Same names are OK, but parameter types must be different public static void main(int x, int y) Need an example!

37 Overloading Constructors and Methods (2)
Java matches argument types with parameter types to choose the right constructor or method to invoke Called overloading: we’re overloading the meaning of the method name Many built-in classes use constructor and method overloading (see println in

38 Example: Improving isPalindrome
public class Palindrome { static boolean isPalindrome(String s) { if (s == null || s.length() <= 1) return true; while (s.length() > 1) { char first = s.charAt(0); char last = s.charAt(s.length() - 1); if (first != last) return false; s = s.substring(1, s.length() - 1); } static boolean isPalindrome(int x) { return isPalindrome(Integer.toString(x));

39 Special Trick: this() in Constructor
Use this(…) to invoke one constructor from another Must be first line in current constructor Java matches argument types to determine which constructor to call Other constructor returns to calling constructor

40 Example: PurdueStudent (1)
public class PurdueStudent { boolean hasName; String name; int puid; // constructor with int... PurdueStudent(int puid) { this.puid = puid; hasName = false; } // constructor with String and int... PurdueStudent(String name, int puid) { this(puid); this.name = name; hasName = true; // [see next slide…]

41 Example: PurdueStudent (2)
public class PurdueStudent { // [see previous slide…] void printStudent() { if (hasName) System.out.println(name + ": " + puid); else System.out.println("(no name): " + puid); } public static void main(String[] args) { // call int-only constructor... PurdueStudent p1 = new PurdueStudent( ); // call String-int constructor... PurdueStudent p2 = new PurdueStudent("Drake", ); p1.printStudent(); p2.printStudent();

42 Example: Overloader public class Overloader { int calc (double x, int y) { ... return z;} // valid overload, 3 parameters int calc (double x, int y, int z) { // valid overload, 1 parameter double calc (double x) { return q;} // valid overload, 2 parameters, different types int calc (double x, String s) { // INVALID overload, return type is not part of the signature double calc (double a, int b) { }

43 Attacking a Problem Top down (understanding the problem)…
What is the program to do? What are the “big steps”? How would you solve it without a program? Bottom up (building and testing the pieces)… What “little problems” can you solve and test? What Java classes and objects can you use? What classes and methods do you need to build?

44 Working as a Team Collaboration requires dividing up the work
In Java, this division is often on class boundaries Alice writes class ImageManipulation Bob writes class ReadWriteImages Alice doesn’t worry about how Bob reads and writes the images Bob doesn’t worry about how Alice does the image manipulation One of the challenges of team programming is deciding how to divide the problem into classes that can be programmed independently.

45 Encapsulation Java supports team work through encapsulation
A form of information hiding or “need to know” Encapsulation serves two purposes Hides implementation details from other programmers, allowing the author to make changes without affecting other programmers Prevents other programmers from modifying certain fields or calling certain methods that might leave the object in an inconsistent or unexpected state Alice knows that Bob can’t mess with her attributes.

46 Java Access Modifiers Can apply to members: fields and methods
Modifiers control access to members from methods in other classes This list is from least to most restrictive: Keyword Restriction public None (any other method can access) protected Only methods in the class, subclasses, or in classes in the same package can access [none] Only methods in the class or in classes in the same package can access (called “package private”) private Only methods in the class can access Sorry, you’ll just have to memorize this chart.

47 Conventional Wisdom Make methods public Make fields private
Allows anyone to use them They should be written defensively to “protect” the object internal state (i.e., attribute fields) Make fields private Keeps them safe from unexpected changes Only your methods can modify them Constants (“final” fields) can be made public since they can’t be changed anyway

48 Accessor and Mutator Methods
With fields being private, all access to them from outside the class is via methods There is no special Java syntax, just naming convention: Accessor: “get…” access (read) field in an object Mutator: “set…” mutate (change) field in an object Accessor methods allow read-only access Mutator methods allow “controlled” change

49 Better Wheel Class public class Wheel { private double radius; public Wheel(double radius) { this.radius = radius; } public double getCircumference() { return 2 * Math.PI * radius; public double getArea() { return Math.PI * radius * radius; public double getRadius() { return radius; public void setRadius(double r) { if (r>0 && r<=1000) radius=r;

50 Using Accessor and Mutator Methods
public class Transportation { public static void main(String[] args) { Wheel w = new Wheel (17.5); double circ = w.getCircumference(); double rad = w.radius; // not allowed double rad = w.getRadius(); w.radius = 15.4; // not allowed w.setRadius(15.4); }

51 Generic Classes An advanced topic to be covered more fully later
Basic idea: A generic class is one that can be parameterized with another class ArrayList<E> is parameterized with class (or type) E. It can only “hold” elements that are references to objects of class E E must be a reference type; primitive types are not supported

52 ArrayList Class A class provided in the java.util package
Dynamic array: automatically grows to accommodate new items Works with any type of object, but you must specify the type when the ArrayList object is created (just like a Java array) Example ArrayList<String> list = new ArrayList<String>(); Creates an empty array of String objects String[] list = new String[10]; On the board: Compare “String[] x = new String[10]” to “ArrayList<String> x = new ArrayList<String>()”. String maps to String, [] maps to ArrayList. You’re getting to the point now where you can start taking more and more advantage of the rich set of classes that Java has available to you. Even if you don’t know how to implement a dynamically growing array like this one, you can take advantage of the someone else’s effort.

53 ArrayList Class Unlike Java arrays, ArrayList does not work with primitive types, only reference types Can’t say “ArrayList<int> list” Fortunately, Java provides special “wrapper” classes for each primitive type Can say “ArrayList<Integer> list” Java handles the conversion between wrapper class and corresponding primitive type

54 Useful ArrayList Methods
add(e) – adds e to end of list add(i, e) – adds e at index i (0-based), pushing others down contains(e) – returns true if e is in the list get(i) – returns the value at index i remove(e) – removes e from the list set(i, e) – adds e at index i, replacing what was there size() – returns the current size of the list

55 Example: ArrayListDemo
import java.util.ArrayList; import java.util.Scanner; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String s = in.nextLine(); list.add(s); } System.out.printf("read %d lines\n", list.size()); for (int i = 0; i < list.size(); i++) { System.out.printf("%s\n", list.get(i));

56 TreeList Class import java.util.ArrayList; public class TreeList { public static void main(String[] args) { ArrayList<Tree> forest = new ArrayList<Tree>(); while (Math.random() < 0.9) { Tree t = new Tree(Math.random() * 100); System.out.printf("tree has radius %.3f\n", t.getRadius()); forest.add(t); } System.out.printf("created %d trees\n", Tree.getNumberOfTrees()); System.out.printf("list has %d trees:\n", forest.size()); for (Tree t : forest) System.out.printf("tree with radius %.3f\n", t.getRadius());


Download ppt "CS18000: Problem Solving and Object-Oriented Programming"

Similar presentations


Ads by Google