Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.

Similar presentations


Presentation on theme: "Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William."— Presentation transcript:

1 Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William Loftus

2 Agenda Variables Primitive vs. Object Types Keyword static Copyright © 2012 Pearson Education, Inc.

3 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Variables Fields are one sort of variable –They store values through the life of an object –They are accessible throughout the class Methods can include shorter-lived variables (parameters and local variables) –They exist only as long as the method is being executed –They are only accessible from within the method

4 Fields / Instance Data A variable declared at the class level (such as x ) is called instance data or a field A field declares the type of the data, if it is an object type (a class) it does not create the object –We need to use new to call a constructor and assign it to that variable Objects of a class share the same method definitions, but each object has its own data space That's how two objects can have different states 10 x 25 y x 45 y

5 Parameters Often, we do not know the values the user will need to use in the constructor, or in any method So we use a variable in the parameter list; the name of the variable is called a formal parameter The value the user/programmer passes to the method, the value that will be stored in the formal parameter, i.e. 500, is the actual parameter

6 Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header public char calc(int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc(25, count, "Hello"); Copyright © 2012 Pearson Education, Inc.

7 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Parameters Formal parameters are only available to use in the method that declares it For example, int num1 and num2 can only be used in the calc method, not in any other method In technical language, we say the scope of the parameter is restricted to the body of the constructor or method in which it is declared

8 Local Data As we’ve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) Keep in mind that instance variables, declared at the class level, exists as long as the object exists Copyright © 2012 Pearson Education, Inc.

9 To “keep” data, store it in fields Local data that will disappear So we need to store it in the fields

10 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Local variables public int refundBalance() { int amountToRefund; amountToRefund = balance; balance = 0; return amountToRefund; } A local variable No visibility modifier Remember: No type when using variables

11 Local variables

12

13 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope of Variables Scope – the set of curly braces in which the variable can be used Examples: –Formal parameters & local variables The scope is the method –Fields The scope is the entire class definition

14 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope Example public class TicketMachine { public TicketMachine(int ticketCost) { price = ticketCost; balance = 0; total = 0; } // Rest of class omitted } { Scope of ticketCost

15 Scope Example: Undergraduate Identify scope of: –Fields –Parameters –Local variables

16 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Scope and life time The scope of a local variable is the block it is declared in The lifetime of a local variable is the time of execution of the block it is declared in Lifetime is dynamic & determined precisely at runtime, whereas scope is static

17 Variable Lifetime Lifetime of a variable = when does the variable exist? What happens if you call the a method (with a parameter) more than once? –The lifetime of a parameter is limited to a single call of the method. –If you call the method more than once, the parameter is created, then removed once the method is done. –Thus, if you have 5 methods calls, the parameter is created 5 times. What is the lifetime of a field? –Is the same as the lifetime of the object –The field is created when the object is created and destroyed when the object is removed

18 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Variable Recap Types of variables –Fields –Parameters –Local variables Scope & lifetime

19 Primitive vs. Object Types What are the difference between object and primitive types? –8 primitive data types (all start with lower case) –A library of classes, and we can make our own (all start with upper case) Are there more differences though?

20 38 45 Object Types & References A primitive variable contains the value itself, but an object variable contains the address of the object An object reference can be thought of as a pointer to the location of the object Rather than dealing with arbitrary addresses, we often depict a reference graphically "Steve Jobs" String name1 int num1 Copyright © 2012 Pearson Education, Inc. object type primitive type "Bill Gates" null

21 Assignment (Primitive types) The act of assignment takes a copy of a value and stores it in a variable For primitive types (e.g. int): num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After: Copyright © 2012 Pearson Education, Inc.

22 Assignment: Object/reference Types For object references, assignment copies the address (e.g. String): name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Wozniak" name1 name2 After: "Steve Jobs" Copyright © 2012 Pearson Education, Inc.

23 Aliases Two or more references that refer to the same object are called aliases of each other That creates an interesting situation: one object can be accessed using multiple reference variables Aliases can be useful, but should be managed carefully Changing an object through one reference changes it for all of its aliases, because there is really only one object Copyright © 2012 Pearson Education, Inc.

24 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Quiz: What is the output? int a; int b; a = 32; b = a; a = a + 1; System.out.println(b); Person a; Person b; a = new Person("Everett"); b = a; a.changeName("Delmar"); System.out.println( b.getName());

25 Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Primitive vs. Object Types 32 ObjectType a; int a; ObjectType b; 32 int b; b = a;

26 Ellipse/Rectangle Examples grass 100 x 200 y fillColor red {255,0,0} 250 width 75 height sun 10 x 25 y fillColor blue {0,0,255} 60 width 75 height

27 Garbage Collection When an object no longer has any valid references to it, it can no longer be accessed by the program The object is useless, and therefore is called garbage Java performs automatic garbage collection periodically, returning an object's memory to the system for future use In other languages, the programmer is responsible for performing garbage collection Copyright © 2012 Pearson Education, Inc.

28 Static Class Members Recall that a static method is one that can be invoked through its class name For example, the methods of the Math class are static (also called class methods): result = Math.sqrt(25) Variables can be static as well Copyright © 2012 Pearson Education, Inc.

29 The static Modifier We declare static methods and variables using the static modifier It associates the method or variable with the class rather than with an object of that class –Static methods are sometimes called class methods –Static variables are sometimes called class variables Copyright © 2012 Pearson Education, Inc.

30 Static Variables Normally, each object has its own data space, but if a variable is declared as static, only one copy of the variable exists private static float price; Memory space for a static variable is created when the class is first referenced Using the final modifier you can also create static constant values (e.g. Math.PI and Color.RED) All objects instantiated from the class share its static variables Changing the value of a static variable in one object changes it for all others Copyright © 2012 Pearson Education, Inc.

31 Static Variable Example (Ellipse) moon x y fillColor red {255,0,0} 100 width 100 height sun 10 static x 25 static y fillColor blue {0,0,255} 60 width 60 height

32 Static Methods Because it is declared as static, the cube method can be invoked through the class name: value = Helper.cube(4); Copyright © 2012 Pearson Education, Inc. public class Helper { public static int cube (int num) { return num * num * num; }

33 Static Class Members Recall that the main method is static – it is invoked by the Java interpreter without creating an object Static methods cannot reference instance variables (fields) because instance variables don't exist until an object exists However, a static method can reference static variables or local variables Static methods and static variables often work together The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method Copyright © 2012 Pearson Education, Inc.

34 //******************************************************************** // Slogan.java Author: Lewis/Loftus // // Represents a single slogan string. //******************************************************************** public class Slogan { private String phrase; private static int count = 0; //----------------------------------------------------------------- // Constructor: Sets up the slogan and counts the number of // instances created. //----------------------------------------------------------------- public Slogan (String str) { phrase = str; count++; } continue

35 Copyright © 2012 Pearson Education, Inc. continue //----------------------------------------------------------------- // Returns this slogan as a string. //----------------------------------------------------------------- public String toString() { return phrase; } //----------------------------------------------------------------- // Returns the number of instances of this class that have been // created. //----------------------------------------------------------------- public static int getCount () { return count; }

36 Copyright © 2012 Pearson Education, Inc. //******************************************************************** // SloganCounter.java Author: Lewis/Loftus // // Demonstrates the use of the static modifier. //******************************************************************** public class SloganCounter { //----------------------------------------------------------------- // Creates several Slogan objects and prints the number of // objects that were created. //----------------------------------------------------------------- public static void main (String[] args) { Slogan obj; obj = new Slogan ("Remember the Alamo."); System.out.println (obj); obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj); continue

37 Copyright © 2012 Pearson Education, Inc. continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }

38 Copyright © 2012 Pearson Education, Inc. continue obj = new Slogan ("Live Free or Die."); System.out.println (obj); obj = new Slogan ("Talk is Cheap."); System.out.println (obj); obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj); System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); } Output Remember the Alamo. Don't Worry. Be Happy. Live Free or Die. Talk is Cheap. Write Once, Run Anywhere. Slogans created: 5

39 Quick Check Copyright © 2012 Pearson Education, Inc. Why can't a static method reference an instance variable (field)? Because instance data is created only when an object is created. You don't need an object to execute a static method. And even if you had an object, which object's instance data would be referenced? (remember, the method is invoked through the class name)

40 Recap Variables –Types: fields, parameters, local –Scope & lifetime Primitive vs. Object Types Keyword static Copyright © 2012 Pearson Education, Inc.

41 Homework CodingBat Start studying for exam Understand concepts from Chapters 1-4 Copyright © 2012 Pearson Education, Inc.


Download ppt "Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William."

Similar presentations


Ads by Google