Presentation is loading. Please wait.

Presentation is loading. Please wait.

Phil Tayco Slide version 1.0 Created Oct 2, 2017

Similar presentations


Presentation on theme: "Phil Tayco Slide version 1.0 Created Oct 2, 2017"— Presentation transcript:

1 Phil Tayco Slide version 1.0 Created Oct 2, 2017
More Class Functions Phil Tayco Slide version 1.0 Created Oct 2, 2017

2 Initialization When creating simple variables, we usually set their initial values at declaration: int age = 21; String firstName = “Phil”; double gpa = 3.9; Reasons this is good practice: We avoid accidentally using the variable in expressions that could result in a run-time error We have more control of the program code which helps with debugging Sometimes we may not know what value to put in when declaring the variable We can put in a value to start often representing the value for the variable as its default If we leave it blank, we must set it somewhere in the code before it is used which can be a risk

3 Initialization Initialization is easy to do because it is basically combining an assignment statement with a variable declaration For objects, initialization is not so easy because classes are designed to store multiple values for properties At this point, we’ve simulated initialization of objects by doing the declaration and property settings on multiple lines of code: Student pupil = new Student(); pupil.setFirstName(“Winona”); pupil.setLastName(“Ryder”); pupil.setGpa(3.9);

4 Initialization Initial observations:
Initializing simple variables is convenient because they are done on one line of code and makes the code look cleaner Initialization is considered good programming practice and should be applied no matter if the data type is simple or complex Simulating initialization of objects with multiple lines of code can lead to accidental omission of forgetting to set a property value Sometimes not all property values will be known, yet the entire object should be considered usable Factors to simulate initialization with objects: Be able to initialize with one line of code Initialization format should be consistent so it is as easily recognizable as it is with simple variables Initialization should be able to support setting as many object properties known while ensuring all other properties are still usable

5 Initialization Three examples (Student class has 3 properties):
Student s1 = new Student(); Student s2 = new Student(); Student s3 = new Student(); s1.setFirstName(“Phil”); s1.setLastName(“Tayco”); s2.setFirstName(“Jane”); s2.setLastName(“Doe”); s2.setGpa(4.0); We may only know this much information: s1 only sets the first and last name. GPA may not be known by the programmer s2 has all properties explicitly set, but that isn’t always the case s3 properties haven’t been set yet Can we simplify the code to satisfy all 3 object initializations? Notice the parentheses…

6 Initialization The parentheses indicate use of a function call
The function in this case is designed to handle object initialization The challenge is that we need to support multiple possible ways to set property values (0, 2 or 3 values at a time) Functions can support this because they can handle multiple input parameters Student s1 = new Student(“Phil”, “Tayco”); Student s2 = new Student(“Jane”, “Doe”, 4.0); Student s3 = new Student();

7 Constructors These functions are a special type of function in the OO world called “constructors” Their purpose is to initialize the properties of an object at declaration On the class design side, they look almost like a regular function. Here’s the constructor that is called when s1 is instantiated: public class Student { public Student(String f, String l) firstName = f; lastName = l; gpa = -1.0; }

8 Constructors The values passed in to the constructor are used to set the property values like a “set” function would Constructors look like regular functions with the following rules: The name of the function must exactly match the name of the class There is no return type with a constructor (not even void) This allows for the code from the calling side to be easily recognizable and all on one line A value for GPA was not handled in this constructor. What value was chosen to set it to? Notice also that there were 3 different ways we created the object using a constructor. How did they differ? How do they appear to be the same?

9 Constructors They are the same in that they have the same function name – all are called by “Student(…” They differ in that each one varies in the number of input parameters (technically, their input parameter types differ) The constructor for s2 looks like this: public class Student { public Student(String f, String l, double g) firstName = f; lastName = l; gpa = g; }

10 Constructors How did the language know to use this constructor for s2 over the one that s1 is using? Technically, the signatures differ by their input parameter types The one used by s1 is (String, String) The one used by s2 is (String, String, double) What is the signature for the one used by s3? public class Student { public Student() firstName = “”; lastName = “”; gpa = -1.0; }

11 Overloading The process of defining multiple functions with the same name but differ in input parameter types is called “method overloading” OO languages look at the input parameter types when function calls are made. If a signature match is found, program executes continues with that function If no match is found, you get a compile error Overloads work only with functions of the same name Return types can differ and most languages do not review return type when looking for matching function signatures Function overloading is often found with constructors, but the rules apply to all functions you design in a class

12 Overloading You can have as many constructor functions as you like to design: public class Student { public Student(double g) firstName = “”; lastName = “”; gpa = g; } public Student(String n) space = n.indexOf(‘ ‘); firstName = n.substring(0, space – 1); lastName = n.substring(space + 1); gpa = -1.0;

13 Overloading Overloading does not look at variable names:
public class Student { public Student(String f, String l) firstName = f; lastName = l; gpa = -1.0; } public Student(String l, String f) This would cause a compile error since both functions have the same signature

14 The other factor Now that we know how to initialize objects with one line of code and provide multiple ways to support constructor through overloading, we can look at the 3rd factor previously mentioned Programmers using our Student class may have situations where they can’t set all property values at instantiation The class design likely will not want to force the programmer to provide a value for all properties at instantiation At the same time, the object after it is created should have all properties be considered evaluable It is still possible to have a value not explicitly set by the programmer, but that should not prevent from “getting” a value that can lead to a run time error

15 The other factor In other words, when we initialize an object, we should set values to all its properties, regardless of whether or not a value is provided by the programmer s2 is explicitly setting all values at construction. That’s great, but likely is not always going to be the case s3 has nothing set and s1 has all but one set (gpa) – what values should go in here in the meantime? In the examples, we set gpa in these situations to -1.0 and firstName and lastName to “” Could we have selected different values? Absolutely! Is one value better than the other? It depends! What do these values in context represent?

16 Defaults We call these values “defaults”
Default values are determined by the class designer and represent a value given to the object at instantiation when a value is not provided When a class is instantiated, the context will vary One program may use Student to manage class enrollment – GPA may not be needed Another program may use Student to measure university performance – GPA is a key property Constructors with no input parameters are using all default values for each property and are known as “default constructors” Good programming practice is to at least define a default constructor when designing a class How does the programmer using this class know when to use what and what defaults they are going to get? Documentation!

17 Constructor Summary As the class designer, you can write as many constructor functions as you want to provide The purpose of the constructor is to “initialize all properties of an object at instantiation” Default values should be used and documented when constructor input values are not known The class designer does not, and should not, know how objects of the class will be used. Constructors are just another form of function capability provided by the designer Programmers using classes should be given the expectations on what functions are available and what default values to expect (normally provided in the documentation with the class Application Programmers Interface (API))

18 Additional Info Creating objects using constructors and manipulating/reading property values with set/get methods are very useful Much flexibility is now available to the programmer using these classes, but that can be a lot of repeated and unnecessary work by the different programmers To see if a Student has a passing GPA, they have to get the GPA and examine its value To see if a Student is an adult, they have to get the date of birth and do some math to determine the age To see if a Student enrolled in a given year, they have to get the ID or registration date and evaluate from there

19 Additional Info Put another way, these questions can be handled by the class: True or false: does the Student have a passing GPA? True or false: is the Student an adult? True or false: did the student register in a given year? These are the questions that are best handled with an OO approach and is a key element in OO design and programming The code for this is handled and provided by the class and promotes code reuse (different programmers don’t necessarily have to write the same logic to determine if the Student is an adult or has a passing GPA) The code becomes more readable and can follow a more natural logical flow (if the Student is passing, do x, y, and z…)

20 Additional Info As before, these capabilities take the form of class functions (methods): public class Student { public boolean isPassing(double passingGrade) return (grade >= passingGrade); } public boolean isAdult() return (age >= 21);

21 Additional Info Using these functions on the object side becomes more natural and readable: Student me = new Student(“Phil”, “Tayco”, 3.5); if (me.isPassing(3.0)) System.out.println(me.getFullName() + “ is passing”); else System.out.println(me.getFullName() + “ is failing”); Observations: isPassing is taking an input parameter to signify the value the programmer is using to signify passing – why is this a useful approach? The output to the end user is by the object programmer – why isn’t this handled by the isPassing function? Where did the getFullName function get defined? We haven’t seen it coded in these examples yet – does that mean this code is wrong?

22 Additional Info Methods driven by data provided by the object programmer can be useful and introduce flexibility – as the class designer, it’s up to you what you want to provide The output to the end user should not come from the class. This keeps the class as “stand-alone” and can be used in multiple contexts (user interface, command line output, or web pages…) getFullName function hasn’t been defined but when looking at this code, you can get a sense of what it is going to do when it is coded. This allows you to focus on the program logic and come back to the details of each function later

23 Predicate functions Functions that return a boolean value to address a particular object state are called “predicate functions” Predicate functions can address any question you see fit and are best designed to handle one situation (isPassing should not be concerned with whether or not the Student has a name) They usually return a boolean to support the separation of end user with class code (no println calls unless for debugging purposes!) Can predicate functions be overloaded?

24 Exercise 3 Create a class that models a GroceryItem
For our class GroceryItem model, we will say that each one has a name (String), selling price (double) and may have an expiration date (String) Create the class with the following functions: Set/get methods for each property 1 default and 2 other constructors of your choice – determine your own default values as you see fit 1 predicate method to see if the GroceryItem is expensive (defined as the selling price is greater than a given price) 1 predicate method to determine if the GroceryItem has an expiration date Next, write a main program that creates at least 2 GroceryItem objects and tests all functions designed


Download ppt "Phil Tayco Slide version 1.0 Created Oct 2, 2017"

Similar presentations


Ads by Google