1 CS257 Computer Science II Kevin Sahr, PhD Lecture 5: Writing Object Classes Object Class 2 objects are the basic building blocks of programs in Object Oriented Programming (OOP) languages objects consist of attributes and behavior the attributes and behavior are defined in the object class attributes are represented by instance variables behavior consists of the constructors and instance methods the class is a blueprint or template for creating objects every object is an instance of some class 3 EX: LightSwitch Class the LightSwitch class is a template for creating objects that represent light switches the complete class source code, the API, and a program that uses the class are on the website we ll briefly review the class, and then enhance it with new Java features Basic Class Concepts: Parts 4 the LightSwitch class illustrates the 3 major parts of an object class: instance variables constructors instance methods
Basic Class Concepts: Encapsulation 5 the LightSwitch class implements the important OOP concept of encapsulation encapsulation is an important concept in OOP languages, defined by: restricting access to the object internals instance variables are private providing an external interface to those internals as appropriate using service methods public getters/setters (accessors/mutators) provided as appropriate EX: No ison Setter 6 note that the API does not contain a setter for the ison instance variable this means that the designer of the LightSwitch class decided not to allow external users to directly change that value Variable Scoping 7 all variables are defined at the smallest possible scope Instance variables are only created for object state that requires a value for the entire existence of the object variables are declared as local variables whenever possible EX: String s in tostring More OOP features of Java 8 now let s use some new OOP features and Java syntax to improve our basic LightSwitch class to create the class LightSwitch2 the secrets of the tostring() method instance variable initialization this reference helper/support methods class variables and constants class methods method overloading
///// private private ///// public { ison public { ison ///// private private ///// public public { the tostring method revisited the LightSwitch has a tostring method returns a String describing the current state of the object makes it easy to take a snapshot of the object state Note: tostring is automatically invoked when the string is an argument to System.out.println/print used in String concatenation EX: System.out.println(obj); is equivalent to: System.out.println(obj.toString()); 9 Instance Variable Initialization instance variables can be initialized in constructors but if the value is known at compile-time, instance variables can also be initialized when declared, just like other variables allows specifying default values for instance variables no need to duplicate the initialization in multiple constructors good idea to use instance variable initialization when possible ensures that the variable has a value (without relying on the constructor) ensures there is only one consistent default value 10 Example LightSwitch instance variables and first two constructors: instance data variables boolean ison; int ; constructors LightSwitch () = false; // originally "off" = 0; // not switched yet // method LightSwitch 11 LightSwitch (int In) = In; = false; // originally "off" // method LightSwitch Example can be rewritten using instance variable initialization in LightSwitch2: 12 instance data variables boolean ison = false; int = 0; constructors LightSwitch2 () { LightSwitch2 (int In) = In; // method LightSwitch2
int ison int this.ison this. The this Reference 13 The this reference allows an object to refer to itself used inside an instance method, it refers to the object upon which the method was invoked EX: Suppose the this reference is used inside a method called tryme, which is invoked as follows: obj1.tryme(); obj2.tryme(); Inside tryme()the this reference refers to obj1 in the first invocation; in the second it refers to obj2 Avoiding Naming Conflicts 14 public LightSwitch (boolean ison, int ) Constructor for a LightSwitch with the specified on-state and number of times flipped. public LightSwitch (boolean isonin, In) { compiler must = isonin; be able to = In; distinguish between // method LightSwitch argument and instance variable 14 The this reference and Naming Conflicts The this reference can be used to distinguish the instance variables of a class from corresponding method arguments with the same names common in constructors and setters 15 argument names can match those in the API public LightSwitch2 (boolean ison, ){ = ison; = ; // method LightSwitch2 Helper/Support Methods 16 all of the methods we have seen so far have been service methods public visibility meant to provide capabilities to external users of our class often it is useful to define methods that are used internally by methods in the class can replace code that is duplicated in multiple service methods can simplify the logic of the service methods we call these methods helper or support methods private visibility not available to external users of our class not listed in the class API
if s s s return String if s s return Helper Method Example the LightSwitch tostring method includes some code that assigns a String to the ison state: public String tostring() { String s = new String("The switch is "); 17 (ison) = s + "ON"; else = s + "OFF"; = s + " and has been flipped " + + " times."; s; // method tostring Example in LightSwitch2 let s create a helper method to do that part: 18 private String isonstring() { s; (ison) = "ON"; else = "OFF"; s; // method isonstring Example 19 now the LightSwitch2 tostring method simplifies to: public String tostring() { return "The switch is " + isonstring() + " and has been flipped " + + " times."; // method tostring Static Class Members 20 Recall that a class (or static) method is one that can be invoked through its class name For example, the methods of the Math class are static: result = Math.sqrt(25) Variables can be static as well referred to as class variables Determining if a method or variable should be static is an important design decision
The static Modifier 21 We declare class methods and variables using the static modifier the method or variable is associated with the class, rather than with a specific object of that class Let's carefully consider the implications Instance Variables Review 22 instance variables are associated with class instances: objects of that class Each object has its own copy of all instance variables defined in the class Memory is allocated for the object s instance variables when the object is instantiated (using the new operator) Changing the value of one object s instance variable has no effect on any other objects Class Variables 23 class variables are declared with the keyword static private static float someclassvar; only one copy of each class variable exists memory for each class variable is allocated when the class is first referenced all instances of the class share its class variables changing the value of a class variable in one object changes it for all others there is only one! Visibility of Class Variables 24 like instance variables, encapsulation warrants that most class variables be declared private exception: if a class variable is a constant it can be public since a constant can t be changed by external (or internal) users, this doesn t break encapsulation EX: the Math class contains a constant class variable declared: public static final double PI = 3.141592653589793; external users can access this constant as Math.PI
EX: Adding a Constant 25 let s say that at most 100 lights can be on at the same time since we don t want to use magic numbers, let s add a constant to LightSwitch2 public static final int MAX_LIGHTS_ON = 100; external users can access (but not change) the value of this constant using LightSwitch2.MAX_LIGHTS_ON public constants should also be added to the API Constants public static final int MAX_LIGHTS_ON The maximum number of lights than can be on at one time. Class Variables EX now let s add a class variable to LightSwitch2 to keep track of how many light switches are currently on 26 to enforce encapsulation the class variable will be private we ll define a public class method to provide the value to external users - since it s public, we ll also add it to the API we intentionally won t create a method that let s external users change the value Class Variables EX Code 27 first declare and initialize the class variable: private static int numlightson = 0; define a class service method to provide the value to external users: public static int getnumlightson () { return numlightson; Class Methods and Variables 28 class methods and class variables often work together class methods are not associated with a particular object instance, so they can not use instance variables but a class method can use class variables note: instance methods can use class variables (as well as instance variables)
Class Variables EX (continued) 29 we also need to find every method in LightSwitch2 where a light is turned on or off and update numlightson accordingly there are two: the third constructor and the flip method we also need to make sure we don t have too many lights on since we need to do this in multiple places, let s add a helper method turnon that handles the check Class Variables EX Helper Method 30 the turnon helper method: private void turnon() { if (numlightson >= MAX_LIGHTS_ON) System.out.println( ERROR: can not turn on another light."); else { this.ison = true; numlightson++; Class Variables EX Constructor change the third constructor to: 31 public LightSwitch2(boolean ison, int ){ if (ison) turnon(); // try to turn on else this.ison = ison; // set to false this. = ; // method LightSwitch2 Class Variables EX flip method change the flip method to: 32 public void flip() { if (ison) { ison = false; numlightson--; else { turnon(); = + 1; // method flip
Method Overloading 33 Method overloading is the process of giving a single method name multiple definitions If a method is overloaded, the method name is not sufficient to determine which method is being called The signature of each overloaded method must be unique The signature consists of the method name along with the number, type, and order of the arguments Method Overloading 34 The compiler determines which method is being invoked by analyzing the arguments float tryme(int x) { return x +.375; Invocation result = tryme(25, 4.32) float tryme(int x, float y) { return x*y; EX: The println Method 35 The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total); Overloading Methods 36 The return type of the method is not part of the signature That is, overloaded methods cannot differ only by their return type Constructors are often overloaded Overloaded constructors provide multiple ways to initialize a new object
Method Overloading EX the three constructors in LightSwitch2 are an example of method overloading our current flip method takes no arguments and flips the light switch a single time let s add an overloaded flip method that flips the light switch multiple times the method signature will have one argument, rather than zero note that this flip method calls the original (no argument) flip method public void flip(int numtimes) { for (int i = 0; i < numtimes; i++) flip(); // method flip 37 LightSwitch2 EX 38 the source code file LightSwitch2.java, the class API, and a program LightSwitchApp2.java that uses LightSwitch2 objects are available on the class website spend some time looking at this example you can easily test the handling of the max number of lights on by temporarily changing MAX_LIGHTS_ON to a smaller number Account Class EX 39 the Account class is a more complex object class it includes all of the new features discussed in this lecture the source code file Account.java and a program that uses the class (Transactions.java) are available on the class website spend some time understanding this class Lecture 5 Vocabulary 40 this reference helper/support methods class variables method overloading method signature