Phil Tayco Slide version 1.0 Created Oct 2, 2017

Slides:



Advertisements
Similar presentations
Today’s lecture Review of Chapter 1 Go over homework exercises for chapter 1.
Advertisements

Logic & program control part 2: Simple selection structures.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 117 Spring 2002 Review for Exam 2 March 6, 2002 open book, 1 page of notes.
Introduction to C Programming
ECE122 L17: Method Development and Testing April 5, 2007 ECE 122 Engineering Problem Solving with Java Lecture 17 Method Development and Testing.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
CPS120: Introduction to Computer Science
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
C++ / G4MICE Course Session 2 Basic C++ types. Control and Looping Functions in C Function/method signatures and scope.
Working With Objects Tonga Institute of Higher Education.
How to Test Methods Computer Science 3 Gerb Objective: Test methods properly.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
JavaScript: Conditionals contd.
C++ LANGUAGE MULTIPLE CHOICE QUESTION
Egyptian Language School Computer Department
Introduction to Java Import Scanner class to use in our program
Phil Tayco Slide version 1.0 Created Sep 10, 2017
User-Written Functions
Classes and Objects.
Lecture 14 Throwing Custom Exceptions
Chapter 7: User-Defined Functions II
Phil Tayco Slide version 1.0 Created Sep 18, 2017
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Introduction to Computer Science / Procedural – 67130
Yanal Alahmad Java Workshop Yanal Alahmad
Debugging and Random Numbers
Loop Structures.
Phil Tayco Slide version 1.0 Created Nov 6, 2017
Phil Tayco Slide version 1.1 Created Oct 30, 2017
Lecture 4 D&D Chapter 5 Methods including scope and overloading Date.
User-Defined Functions
Lesson 2: Building Blocks of Programming
Comparing Objects Phil Tayco San Jose City College Slide version 1.1
Composition Phil Tayco San Jose City College Slide version 1.2
Phil Tayco Slide version 1.0 Created Oct 16, 2017
ICS 3U Tuesday, September 21st.
Conditions and Ifs BIS1523 – Lecture 8.
Number and String Operations
Phil Tayco Slide version 1.0 Created Oct 9, 2017
Polymorphism Phil Tayco San Jose City College Slide version 1.1
6 Chapter Functions.
Java Programming Arrays
Java Programming Loops
Java Programming Function Introduction
Coding Concepts (Basics)
Java Programming Control Structures Part 1
CS139 October 11, 2004.
Classes and Objects Phil Tayco San Jose City College Slide version 1.1
The Java switch Statement
Chapter 3: Selection Structures: Making Decisions
Boolean Expressions to Make Comparisons
SSEA Computer Science: Track A
Inheritance Phil Tayco San Jose City College Slide version 1.2
Object Comparisons and Arrays
Java Programming Loops
Chapter 3: Selection Structures: Making Decisions
Classes, Objects and Methods
Java Programming Function Introduction
Variables in C Topics Naming Variables Declaring Variables
LCC 6310 Computation as an Expressive Medium
Lecture 3 More on Flow Control, More on Functions,
Intro to Programming (in JavaScript)
Creating and Using Classes
Phil Tayco San Jose City College Slide version 1.2 Updated Sep 9, 2019
Presentation transcript:

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

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

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);

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

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…

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();

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; }

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?

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; }

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; }

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

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;

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

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

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?

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!

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))

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

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…)

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);

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?

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

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?

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