L2 ObjectOrientedProgrammingIntroduction
L2 ObjectOrientedProgrammingIntroduction
Distributed
Information Systems
LECTURE 2 – GIT, OBJECT -ORIENTED PROGRAMMING
Contents
• Object-oriented programming – basic concepts
◦ Classes and objects
◦ Access and access permissions
◦ Constructors
◦ Declaration, instantiation, assignment
◦ Instance methods, static methods
◦ Passing by value and reference
◦ Inheritance
◦ Properties – getters, setters
2
Approach
• We will proceed mostly using simple, intuitive examples
◦ Build up slowly as we motivate the need for various OOP concepts
3
Object-oriented programming
• Motivation
◦ Computers natively handle primitive data types
◦ But developers and end users typically need to work with more expressive
data types
◦ E.g. people, organizations, courses, programs etc
4
Motivation example
• Primitive programming
◦ string firstNameUser1 = "John";
◦ string lastNameUser1 = "Doe";
◦ string nameCourse1 = "ISM 6225";
◦ registerCourse(nameCourse1, firstNameUser1);
• Object-oriented programming
◦ User User1 = new User("John");
◦ Course Course1 = new Course("ISM 6225");
◦ Course1.Register(User1);
5
Motivation example (contd.)
• Without object oriented programming
◦ Variables associated with the same entity are not naturally associated in the
program
◦ E.g. first name and last name strings
◦ Business operations are not naturally associated with the entities they work
with
◦ E.g. course registration
6
Object-oriented programming basics
• Languages which support object-oriented programming (OOP) allow
programmers to define classes
◦ Classes can have variables inside them
◦ These variables can themselves be classes
◦ These variables are typically called properties
/// <summary>
/// Define a class for people
/// </summary>
class Person
{
string firstName;
string lastName;
}
7
Classes
• Classes can also have methods
◦ These methods typically act on the class properties
class Person
{
string firstName;
string lastName;
string getName()
{
return firstName + " " + lastName;
}
}
8
Using classes
• Classes can be used in programs just like any other primitive type
• Uh oh
9
Access permissions
• In object-oriented programming
◦ Properties are associated with classes
◦ Appropriate that classes should have control over their properties
◦ Who can see and edit these properties
◦ I should not be able to change your first name
10
Update class with access
permissions
class Person
{
public string firstName;
public string lastName;
11
Using the class
namespace Project02_ObjectOrientedProgramming
{
class Program
{
/// <summary>
/// Define a class for people
/// </summary>
class Person
{
public string firstName;
public string lastName;
12
Accessing the class properties
and methods
• How can we access the firstName, lastName properties and the
getName() method?
• The typical syntax used to access the properties of a class is the dot
notation
◦ <Class>.<Item>
• Say we want to use the getName() method to print the name of the
student
◦ We can use Student.getName()
◦ E.g.
◦ Debug.WriteLine(Student.getName());
13
Exercise
• Add a field to the Person class
◦ Type: string
◦ Name: Salutation
14
Static methods and fields
• Most of the time, we work with instances of classes
◦ E.g. the Student instance of the Person class
15
Example of static property
• Say we limit the available salutations to “Mr”, “Ms”, “Other”
◦ All persons will have one of these salutations (or none)
16
Example of static property
• One possibility is to define these as static properties of the Person
class
static void Main(string[] args)
{
Person Student = new Person { salutation = Person.salutationMr,
firstName = "John",
lastName = "Doe" };
}
class Person
{
public static string salutationMr = "Mr";
public string salutation;
…
}
• This keeps all features of the Person object within the class definition
17
Accessing static properties
• Static properties do not need an instance of the class
◦ They are therefore accessed using the class name
◦ Instead of the instance name
◦ E.g.
◦ Person.salutationMr
18
Constructors
• We created the Student object by directly accessing the properties of
the class
◦ Person Student = new Person { salutation = Person.salutationMr, firstName = "John", lastName = "Doe" };
19
Constructors (contd.)
• Therefore, object-oriented programming supports constructors
◦ Create a new instance of an object
◦ Automatically invoked by the language when a new instance is created
20
Constructors (contd.)
class Person
{
public static string salutationMr = "Mr";
public static string salutationMs = "Ms";
public static string defaultlastName = "NLN";
public Person()
{
firstName = "";
lastName = defaultlastName;
salutation = salutationMs;
}
…
}
21
Constructors – features and usage
• Constructors have two special properties
◦ They have the same name as the class
◦ They do not have a return type
◦ Allows the language to identify the methods as constructor methods
• A class can have any number of constructors
◦ Most frameworks provide a large number of constructors
◦ Allows use of appropriate constructor depending upon information available at the time of object
creation
◦ Missing information filled in with default values
◦ E.g. MVC framework offers constructors to create URLs with
◦ Just the action name (constructor name, HTTP method etc filled by default)
◦ Full specification (allows defining action method, HTTP method, JavaScript parameters, styling
details etc)
22
Constructors – features and usage
• Usage
Person Student1 = new Person();
Person Student2 = new Person(Person.salutationMr, "John", "Doe");
23
Constructors - this
• The problem is that within the constructor, the variable salutation can
refer to two objects
◦ The argument passed to the method
◦ The salutation field of the class
• Resolution
◦ Variables are typically resolved to the most local values
◦ Hence, salutation refers to the argument passed to the constructor
◦ To refer to the salutation field of the object
◦ Use this.salutation
◦ this.salutation = salutation;
◦ this is an OOP keyword in most languages
◦ Refers to the current object instance
24
Exercise
• Check out language default constructor
◦ Comment out all constructors
◦ Create a new Person object
Person Student1 = new Person();
25
Creating objects - definitions
• Declaration
◦ Person Student;
◦ Creates storage space to refer to the object
◦ No object created yet
• Instantiation
◦ new Person();
◦ Creates the object
◦ But no access to it, cannot be used in the program
• Assignment
◦ Student = Student1;
◦ Variable refers to object
26
Typical usage
• Combine all three
◦ Person Student2 = new Person(Person.salutationMr,
"John", "Doe");
1. Declares variable Student2 as object of class Person
2. Instantiates a new Person object
3. Assigns the Person object to Student2 variable
27
Passing by value and reference
• One key difference in treatment of primitive variables and objects
• Motivation is to conserve resources
◦ Primitive variables are passed by value
◦ Objects are passed by reference
• Consider 2 examples
28
Passing by value and reference
PASSING BY VALUE PASSING BY REFERENCE
Person Student3 = new Person(Person.salutationMs, "Jane", "Doe");
int testVar1 = 3; Person Student4 = modifyArgumentperson(Student3);
int y = modifyArgument(testVar1);
Debug.WriteLine(Student3.lastName + ", " + Student4.lastName);
Debug.WriteLine(testVar1 + ", " + y);
29
Passing by value and reference
• When passed by value
◦ A copy of the variable is created
◦ Changes to the variable within the called method do not change the value
in the calling method
30
Inheritance
• Also seen as specialization
• Many business objects share properties with more general objects
◦ But have special properties of their own
• E.g.
◦ All students are persons
◦ getName() is relevant to students just as well as any generic person
◦ But all students have student numbers, whereas a generic person does not need one
◦ All students have a major, but a generic person may not
31
Inheritance
• We could create separate classes for Person and Student
◦ Will work
◦ But lose the relationship between Person and Student
◦ Also, will lead to method duplication
◦ Multiple implementations of getName()
◦ Can lead to lost updates
◦ E.g. if we decide to update getName(), we will need to remember all the different
implementations to update
32
Implementing inheritance
class Student : Person
{
public string studentNumber;
public Student()
{
studentNumber = "U1234";
firstName = "";
lastName = defaultlastName;
salutation = salutationMs;
}
}
33
Implementing inheritance
• The above works
◦ But has some limitations
◦ We have essentially repeated the constructor of the Person object
◦ What happens if that constructor evolves?
◦ We would like to make changes in just one place if something changes
34
Updated Student class
class Student : Person
{
public string studentNumber;
public Student(string sNumber, string sal, string ftName, string ltName) : base(sal, ftName, ltName)
{
studentNumber = sNumber;
}
35
Using the student class
• An inherited class is used just like the parent class
◦ And really, almost like a primitive type
◦ Of course, with the dotted notation and passing by reference
36
Final touches
• Thus far, we have worked directly with the class fields
◦ firstName, lastName etc
37
Using getters and setters
private string SSN;
• Person1.setSSN("123");
38
C# approach
• C# allows you to define and use properties using a friendly syntax
◦ Combines both worlds
• Since the typical getters and setters follow a very specific pattern
◦ Compiler can hide the complexity from developers
◦ Use the getter and setter methods
◦ But allow developers to access the properties directly
39
Exercise
• Change all existing fields to properties
◦ Add the get and set methods
40
Example of using objects
• As an example of using objects, let us consider a Linked List
◦ Subject of assignment 2
41
Some useful references
• Introduction
◦ Wikipedia: https://en.wikipedia.org/wiki/Linked_list
◦ CMU: https://www.cs.cmu.edu/~adamchik/15-
121/lectures/Linked%20Lists/linked%20lists.html
• C# implementation example
◦ http://adt-csharp.blogspot.com/2016/09/list-adt-linked-list-
implementation.html
42
Linked Lists
• Definition
◦ A linear collection of data nodes, where each node contains a value and a
reference to the next data node
• Importance
◦ Almost any data in a computer that is of arbitrarily varying length is stored
as a linked list, e.g.
◦ Files list
◦ Processes list
◦ Program stack
• Many specialized data structures are linked lists with constrained set
of operations
◦ E.g. stacks, queues
43
Stock portfolio as object
• Consider the stock portfolio of a client
◦ It has
◦ Client information
◦ Potentially, portfolio value for quick reference
◦ A list of stocks
Client Portfolio
Client information
Portfolio value
Stock List
Stock node Stock node Stock node
Head Stock Stock Stock Head
44
Using these objects
• When a client joins a firm
◦ Create a new portfolio object
◦ Constructor initializes
◦ Client information, portfolio value
◦ New Stock list object
• Note
◦ A more complete application can maintain a list of transactions for each stock
◦ To maintain trade history
45
Stock class
public class Stock
{
public string Symbol { get; set; }
public string Name { get; set; }
public decimal Holdings { get; set; }
public decimal CurrentPrice { get; set; }
// default constructor
public Stock()
{
Symbol = "NA"; Name = "Invalid"; Holdings = 0; CurrentPrice = -99;
}
46
StockNode class
public class StockNode
{
public Stock StockHolding;
47
StockList class
public class StockList
{
private StockNode head;
/*
* param : NA
* summary : checks if the list is empty
* return : true if list is empty, false otherwise
* return type : bool
*/
public bool IsEmpty()
{
if (this.head == null)
{
return true;
}
return false;
}
}
48
Example StockList methods
/*
* param (Stock)stock : stock that is to be added
* summary : Add node at first position in list
* return : NA
* return type : NA
*/
public void AddFirst(Stock stock)
{
StockNode nodeToAdd = new StockNode(stock);
nodeToAdd.Next = head;
head = nodeToAdd;
}
49
Example StockList methods
/*
* param (Stock)stock : stock that is to be added
* summary : Add mode at last position of list
* return :
* return type :
*/
public void AddLast(Stock stock)
{
if (this.IsEmpty())
AddFirst(stock);
else
{
StockNode current = this.head;
while (current.Next != null)
current = current.Next;
50
Example StockList methods
/*
* param (Stock)stock : stock that is to be checked
* summary : checks if list contains stock passed as parameter
* return : Reference of node with matching stock
* return type : StockNode
*/
public StockNode Contains(Stock stock)
{
StockNode nodeReference = null;
if (this.IsEmpty())
return nodeReference;
else
{
StockNode current = this.head;
StockNode previous = this.head;
while (current.Next != null)
{
Stock currentStock = current.StockHolding;
if (currentStock.Equals(stock))
{
nodeReference = previous;
break;
}
previous = current;
current = current.Next;
}
}
return nodeReference;
}
51
Assignment 2
• The assignment asks you to write a few methods to develop familiarity
with Linked Lists and Object Oriented programming
• Requirement
◦ The group must use Github to collaborate
◦ Last exercise asks you to report on the number of lines contributed by each team member
◦ Companion site has a video that shows how to use Github
◦ Recommendation 1: Add your Github link to your EdvisionApp profile
◦ And resume
◦ Recommendation 2: Use Giithub for all your coding projects in the program
◦ And any other suitable use cases
◦ Build a demonstrable repository
52
Git
• All professional developers are expected to be comfortable using a
source control and collaboration system
◦ E.g. Perforce, Git
◦ Maintain code history
◦ Simplify sharing code with collaborators
◦ Think of it as a super-charged version of online documents
53
Git
• Check out videos on companion site:
◦ http://www.ismlab.usf.edu/dis/
54
Steps
• Create a Github account
• Follow Github getting started guide
◦ https://guides.github.com/activities/hello-world/ (Fall 2018)
55
Exercise
• Create a Github account if not already done
56
References
• Josh Hug, CS 61B slides, UC Berkeley, https://sp18.datastructur.es/
57