Download presentation
Presentation is loading. Please wait.
Published byIris Hampton Modified over 5 years ago
1
Classes and Objects Phil Tayco San Jose City College Slide version 1.1
Updated Sep 10, 2018
2
Primitive Data Types All variables are defined with a data type and variable name int age = 21; double gpa = 3.9; Memory for age and gpa is instantly allocated and contents are initialized Process is automatically done because the language already knows these simple data types All variables in memory have a location, but knowing exactly where they are is not important for primitives Advantages arise when knowing how these memory locations can be used age 21 gpa 3.9
3
Memory References Memory locations can be referred to by other variables (in C/C++, this is called a “pointer”) A memory reference is essentially a variable that contains a memory address as its value The value refers to a memory location where information is stored When memory references are defined, the location it is pointing to must be reserved (a.k.a. memory must be “allocated”) Modern programming languages have “no pointers”, but in fact they are handling a lot of the pointer process automatically for you C and C++ gives you more memory management control, which can be both a blessing and a curse!
4
Memory References Memory references are useful when handling complex data In Java, memory reference management is automatically done by default when you use data types that are not primitive Exception: String data types are technically treated as complex data types, but can be used the same way as primitives in many ways Java is often referred to as a language with “no pointers”, but in fact it does use memory reference management…it just does a lot of the hard work for you It is important to know the process that occurs behind the scenes as it will become useful to understand later with advanced concepts
5
Memory References When we declare a variable with a complex data type, the memory location it is referring to is yet to be defined Student me; me ?
6
Memory References To allocate the memory, we request it with the “new” keyword Student me = new Student(); When the compiler sees “new Student()” it uses what it knows a Student looks like and looks in memory for a location large enough to store that data 0x1234abcd is an example of a numeric location where the Student data could reside “me” is the variable that now refers to the location of the Student data. In Java, this is transparent to us, but we should know that this structure exists me 0x1234abcd (Student data)
7
Complex Data Types But how does Java know what “a Student looks like”?
Integers and doubles are simple data types because they store one value. (age stores 21 and gpa stores 3.9) Conceptually, a Student can store much more types of information. Think of every Student that you may want to model in a program. Every Student has: First name Last name Age Gpa ID Each one of these elements of a Student is called a “property” (also called an “attribute”)
8
Complex Data Types These properties make up the template for defining a Student In the example, we declared a variable “me” whose data type is “Student” (this is the same as when we declared a variable “age” whose data type is an integer) We assigned age a value of 21 after we declared it. Similarly, we will want to assign values to me’s properties This means Student’s properties are like variables grouped together within (or “encapsulated”) the overall Student variable (“me”) me has its own first name, last name, ID, etc. As such, each property is defined like a variable
9
Complex Data Types public class Student { public String firstName; public String lastName; public int age; public int id; public double gpa; } These properties are defined in a separate Java file called a “class” The file is separate because a class is designed to be a “stand-alone” data type. Put another way, the class is intended to be used by any number of other programs
10
Complex Data Types In another program (such as in the “main” function), we can assign values to these properties for the “me” variable In memory, technically the location where the Student data was allocated is found through the memory address – a process called “dereferencing” Student me = new Student(); me.id = 1234; me.age = 21; me.firstName = “Phil”; me 0x1234abcd firstName “Phil” lastName id 1234 age 21 gpa
11
Complex Data Types You can define as many different variables defined with primitive data types as memory allows (int x, int y, int z, etc.) Similarly, you can define as many different variables with classes (Student me, Student you, Student[] roster, etc.) Variables with primitive types are commonly referred to as just variables. A variable whose data type is a class is called an “object” Objects are seen as “instances” of a class. Creating objects is also called “instantiation” Object-oriented programming is the study of designing solutions primarily through the manipulation of such objects (variables with complex data types)
12
Accessing Properties When a class is designed with the data members public, a binding occurs between the code creating the object of that class and the class’ design Class example: public class Student { public String firstName; public String lastName; public int age; public int id; public double gpa; }
13
Accessing Properties Using that class, objects in other programs set property values directly: Student example = new Student(); example.firstName = “John”; example.id = 123; This makes the object and class code somewhat dependent on each other Changes in code on the use of the object are ok as they won’t affect the class code design – whether or not you use a property, the class code is unaware of its use More importantly, the class code shouldn’t be aware how it’s used! The class is providing capabilities to object creators.
14
Accessing Properties This relationship can be referred to as “high coupling” or “weak encapsulation” Weak encapsulation means that the property information is not hidden because it is available for all to use (they are public) What are some problems with this? If the code changes on the object side, we already saw that doesn’t affect the class code design What about the other way? If we change any part of the design, does that affect the object code?
15
Accessing Properties Absolutely!
public class Student { public String first_name; public String lastName; public int age; public String id; public double gpa; } These simple code changes affects the example object example.firstName has to change to example.first_name example.id = 123 has to change to example.id = “123”
16
Accessing Properties In small amounts of code, this can be manageable, but as programs get larger and object use increases, any change in class code design has more downstream effects Property usage is also a highly performed activity – programs are fundamentally designed to manipulate the variable values and make logical decisions from them It is also hard to predict what complex programs actually need as they evolve (why do we have different versions of Windows? iOS? Microsoft Office?) Classes are also supposed to be stand-alone. New programs using the class may have different needs than as the class originally was designed As requirements change, data types used will evolve
17
Strong Encapsulation Because class properties have such high usage and evolution, another approach is to hide that information from other programs public class Student { private String firstName; private String lastName; private int age; private int id; private double gpa; } This now means any object created as type Student cannot directly access the properties (example.id = 123 would result in a compile error)
18
Strong Encapsulation How are property values manipulated if they are marked as private? In order to see how that is typically done, we must first discuss another aspect to all class designs All classes have properties that define “what objects of that class type will have” In addition, we can define “behaviors” that define “what objects of that class type can do” These behaviors are also referred to as “methods” and they define actions
19
Class Methods We’ve already seen code that define actions such as “calculateArea” or “println” These actions are defined in the form of a function. Recall that a function is defined with 3 parts: function name, return type and input parameters public double calculateArea(double length, double width) { return length * width; } This function is defined with the name “calculateArea”, a return type of “double” and has 2 input parameters that are each “double” data types
20
Class Methods We call the definition of a function a “function signature” and all signatures have these 3 elements Within the function contains the code for performing the overall action it is intended to define We learned that such code is also designed to be stand-alone and hidden. This means whomever calls the function with their code, they don’t need to know what the code actually does (nor should they!) – they only care that it performs as designed We can take advantage of this by defining functions in classes designed to handle property value usage
21
Class Methods public class Student { private String firstName; public void setFirstName(String f) firstName = f; } In this example, the method signature is “setFirstName”. It takes a String as an input parameter and returns nothing (return type is void) Within the function, “f” is a local String variable initialized by the input value where the function was called The goal of this method is to set the firstName property to a given value (stored in f)
22
Class Methods Typical questions arise from this approach
How is this function called? Where and how is “firstName” used? Remember that these functions live within the context of a class A class is used when an object is instantiated of its type Once an object is created, anything defined as public within the class design is usable and will apply to that specific object
23
Class Methods Student me = new Student(); me.setFirstName(“John”); In this example, an object “me” is created of type Student The only thing defined as public in the Student class is the “setFirstName” method When the method is used, it will be in the context of a created object – this means in this case, the setFirstName method will be applied to the “me” object Since the method is a public function, we use it like a function call, sending in a String and not expecting a return value because of the way the method signature is defined
24
Class Methods When the method is called, “John” comes in as an input value that will be assigned to the “f” variable in the setFirstName function public void setFirstName(String f) { firstName = f; } Now the important part: the only line of code in the method is “firstName = f;”. Where is firstName defined? Since it is not defined within the function, we have to look outside the function but still within the code module the function is defined
25
Class Methods That code module is the class itself!
public class Student { private String firstName; public void setFirstName(String f) firstName = f; } That code module is the class itself! This means firstName is accessible to all functions defined within the class Now note that firstName is treated like a variable – we call it a class property, but it is essentially a variable By itself, firstName is definition. It is not a physical variable, until when…?
26
Class Methods …when an instance of the class is created!
“firstName” doesn’t become a physical element in memory until “Student me = new Student();” was created Once that object was instantiated, me.firstName = “John”; could be done to assign “John” to the firstName property of the “me” instance But remember, we made firstName private, so that line of code is not allowed setFirstName is a method that is public, so we will use that By calling the function setFirstName(“John”): “John” is used in the function (through f) f is assigned to the variable firstName firstName represents the property of the me object (because we called it with “me.setFirstName(…”)
27
Class Methods This approach can be used with all class properties
public void setGpa(double g) { gpa = g; } Some questions to note: “gpa” property name is part of the function name “setGpa” – what would the function name be for the id or lastName properties? The input parameter type is “double” which matches the gpa property data type definition. What would the input parameter types be for id and lastName? Why is the return type void? Could the return type be something else? If so, what could it signify?
28
Class Methods This approach promotes code reuse as well. If we create multiple objects, the same code is used within the context of each object: Student one = new Student(); Student two = new Student(); one.setFirstName(“Susan”); two.setFirstName(“Alex”); One and two are physically two separate objects with their own property values Both are using the same code instructions to set their individual firstName properties respectively These particular methods are frequently used and commonly referred to as “setters” or “mutators” – they are functions designed to change object property values
29
Class Methods Could you create set methods that change more than one property at a time? Yes! public void setName(String f, String l) { firstName = f; lastName = l; } What are pros/cons to doing so? Remember, any function created doesn’t always have to be used… Mutators are needed for changing object property values. What about when we need to view the data?
30
Accessing Data Previously, we could look at an object’s property value at any time directly: System.out.println(me.firstName); However, the firstName property is now private We need another way to retrieve that value Put another way, we need a “method” that is designed to “return” the firstName value to us This leads to designing another function. Based on the information here, what would the method signature for seeing the object’s firstName value?
31
Accessing Data Remember the 3 parts to the function signature: name, input parameter types and return type public String getFirstName() { return firstName; } The name of this function (which also states its purpose) is appropriately entitled “getFirstName” The return type is a String meaning that when the function is called, we will get what represents the firstName of the Student object as a String Why are there no input parameters?
32
Accessing Data Just like with the set methods, these get methods are designed to be used for each class property Because the value coming back is through a return value of a function, the get methods are designed to return one property value The return type in this example is a String which matches the definition of firstName in the class. This usually is the case, but remember: The class is encapsulating the definition of the firstName property. This means we can change the name and the type at any time (what would we have to change if we did that?) There are usually no input parameters with get methods because their job is to return existing (and known) information. No new information from the object method call is needed to perform this action
33
Setters and Getters Like setters/mutators, these functions are commonly referred to as “getters” or “accessors” You typically see a get and a set function for each property (a class with 4 properties will usually have 4 accessors and 4 mutators) Their function signatures usually follow a pattern based on the property name and its data type Some classes may not want to have certain accessors/mutators defined – this will depend on the class designer’s intent of use Any number of setter functions can occur. Typically you see one get function per class property
34
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
35
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);
36
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
37
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…
38
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();
39
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; }
40
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?
41
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; }
42
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; }
43
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
44
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;
45
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
46
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
47
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?
48
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!
49
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))
50
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
51
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…)
52
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);
53
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?
54
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
55
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?
56
Programming Exercise 1 Create a class that models a House
For your House class, come up with 5 properties to model and utilize at least 1 String, 1 int and 1 double Add the following methods for your class: Set/get methods for each property 1 default and 2 other constructors of your choice – determine your own default values as you see fit At least 1 predicate method Next, write a main program that creates at least 2 House objects and tests all functions designed from input from the user Show a menu to the user with options for each method and ome up with your own ways to effectively test your House class and objects
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.