0% found this document useful (0 votes)
4 views

9B Gentle Introduction to Objects

Uploaded by

Sophia Lindholm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

9B Gentle Introduction to Objects

Uploaded by

Sophia Lindholm
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Gentle Introduction to Objects

Cosmin E. Oancea
[email protected]

Department of Computer Science (DIKU)


University of Copenhagen

November 2023 KOM-IT Lecture Slides


Today’s Lecture

Short Quiz from Complexity;

Working with arrays and strings;

Creating and modifying objects;

Nesting objects;

Classes and inheritance;

Using objects to implement data stuctures;

Using objects to encapsulate heterogeneous data.


Complexity Quiz
Assume that we have two programs A and B that solve the same problem, and both receive
as input an array of length n. The following table shows the speedup of A in comparison
with B for increasing values of n. The running time of both A and B increases with n.
(The speedup indicates how many times faster is A in comparison with B on a given input.)

n 10000 50000 100000 500000 1000000 5000000 10000000


Speedup 100× 31× 14× 7.3× 6.3× 6.7× 6.2×

It is likely that A and B have the same complexity:

TRUE
FALSE

Please explain why.


Complexity Quiz
Assume that we have two programs A and B that solve the same problem, and both receive
as input an array of length n. The following table shows the speedup of A in comparison
with B for increasing values of n. The running time of both A and B increases with n.
(The speedup indicates how many times faster is A in comparison with B on a given input.)

n 10000 50000 100000 500000 1000000 5000000 10000000


Speedup 100× 223× 316× 707× 1000× 2236× 3162×

It is likely that A and B have the same complexity:

TRUE
FALSE

Please explain why.


Tough Question:
n·(n−1) n2 n
It is known that the sum 0 + 1 + 2 + 3 + . . . + n − 1 = 2
= 2
− 2
Consider the following code:
f u n c t i o n sumUpElementsUpToM ( a r r a y , M) {
let s = 0;
f o r ( l e t i = 0 ; i < M; i = i + 1 ) {
s = s + array [ i ] ;
}
return s ;
}

f u n c t i o n dummyPrefixSum ( a r r a y ) {
let result = [ ] ;
for ( l e t i =0; i < array . length ; i = i +1) {

l e t new elem = sumUpElementsUpToN ( a r r a y , i ) ;

r e s u l t . push ( new elem ) ;


}
return result ;
}

The complexity of the dummyPrefixSum in terms of the length n of the input array is
(a) O( 1 )
(b) O( log(n) )
(c) O( n )
(d) O( n2 )
(e) O( 2n )
Please explain why.
Arrays and Strings
to create a slice of an array arr that contains the elements from position beg up
until and excluding position end use arr.slice(beg, end)

to create an array consisting of the characters in a string str use


Array.from(str)

to split a string txt that consists of multiple lines, into an array of (string) lines, use
txt.split("\n")

similarly, to split a string into an array of strings using space as separator, one can
use txt.split(" ")

joining the (string) elements of an array arr into one big string (with space as
separator between elements) can be achieved with arr.join(" ")

Removing all spaces from a string can be achieved with:


str.split(" ").join("")

keeping only letter, digits, spaces and common punctuation and eliminating all
other (wired) symbols from a string:

s t r . r e p l a c e ( / [ ˆ a−zA−Z0 − 9 .; , ’ − ’ ] / g , ” ” )
Objects

Arrays and strings have the property length;

HTML elements that we get from


document.getElementById(’...’) have the property
innerHTML among others;

An object is a set of named values (a.k.a., properties or fields)


grouped together;

Objects can also be enhanced with functionality, i.e.,


methods that can be called on them.

Data Structures can be implemented nicely as objects:


underlying representation (e.g., an array of strings paired
with a string) + methods (e.g., push, pop).
Making Objects
Syntax. One way to create an object is by using curly brackets as
an expression that is assigned to a variable:
Inside the curly brackets lives a list of properties separated
by commas;
Each property has a name followed by a colon and a value.

l e t g r e a t m o vi e = { t i t l e : ” Jaws ”
, ye a r : 1975
, mins : 124
};
l e t p o s i t i o n = { x : 400 , y : 20 } ;

There are other ways to create objects as well (see next slide).

Please note that different fields of an objects may naturally have


different types, as opposed to arrays, which in principle should
contain elements of the same type.
Other Ways of Creating Objects (You may ignore them)
Another ways is to use new Object() and
to use . to create/set new fields:
l e t g r e a t m o vi e = new O b j e ct ( ) ;
g r e a t m o vi e . t i t l e = ” Jaws ” ;
g r e a t m o vi e . ye a r = 1 9 75 ;
g r e a t m o vi e . mins = 124;

to use [] to create/set new fields:


l e t g r e a t m o vi e = new O b j e ct ( ) ;
g r e a t m o vi e [ ’ t i t l e ’ ] = ” Jaws ” ;
g r e a t m o vi e [ ’ ye a r ’ ] = 1 9 75 ;
g r e a t m o vi e [ ’ mins ’ ] = 124;
Inspecting and Modifying Objects

We can inspect and modify an object by using the dot


(period) operator;
Objects are mutable (like arrays, but unlike strings).

co n s o l e . l o g ( g r e a t m o vi e . t i t l e ) ;

p o s i t i o n . x += 5 0 ;
Nested Objects

Arrays can contain objects;


Objects can contain arrays (as fields/properties);
Objects can contain other objects (as fields/properties).

l e t monster = { name : ” B i g Green ”


, c u r r e n t p o s : { x : 5 0 , y : 10 }
, o l d p o s i t i o n s : [ { x : 4 0 , y : 10}
, { x : 40 , y : 0 }
]
};

monster . o l d p o s i t i o n s [ 1 ] . x −= 1 0 ;
monster . o l d p o s i t i o n s [ 1 ] . y += 5 ;
co n s o l e . l o g ( monster . o l d p o s i t i o n s [ 1 ] ) ;
Object Oriented Programming
Object-oriented programming (OOP) is a programming paradigm
based on the concept of “objects”, which can contain data and
code: data in the form of fields (often known as attributes or
properties), and code, in the form of procedures (often known as
methods).

The core idea is to divide programs into smaller pieces and make
each piece responsible for managing its own state.

This is useful for example in building data-structures, e.g., a


queue data-structure would associate an underlying container
(e.g., array) with the functionality of the enqueue and dequeue
methods.
Classes
c l a s s User {
name ; / / y e t a n o t h e r way t o d e c l a r e a f i e l d

c o n s t r u c t o r ( name ) {
this.name = name ;
}
getName ( ) { / / t h i s i s a method
r e t u r n ”name i s : ” + this.name ;
}
}

l e t u s e r = new User ( ’ John Snow ’ ) ;


l e t obj = {};
u s e r i n s t a n c e o f User ; / / t r u e
o b j i n s t a n c e o f User ; / / f a l s e

co n s o l e . l o g ( u s e r . getName ( ) ) ; / / p r i n t s : ” name i s : J o h n Snow ”

The constructor is the code that gets executed when creating a new object.
Meaning: when you call new User(’John Snow’); this essentially executes
(calls) the constructor of the User class with ’John Snow’ as its argument.
In JavaScript there can be only one constructor per class.
Inheritance
A class can “extend” or “inherit” the functionality of another class.
c l a s s S t u d e n t extends User {
grad courses; / / new f i e l d / p r o p e r t y
c o n s t r u c t o r ( name , c o u r s e s ) {
super(name); / / c a l l s t h e c o n s t r u c t o r o f U s e r
t h i s . g r a d co u r s e s = courses ;
}
addGradCourse(course) {
t h i s . g r a d c o u r s e s . push ( co u r s e ) ;
}
}
l e t s t u d = new S t u d e n t ( ’ H a r r y Po t t e r ’ , [ ’ p o t i o n s ’ ] ) ;
stud.getName(); / / i n h e r i t e d fr o m U s e r
stud.name; / / i n h e r i t e d fr o m U s e r
stud.addGradCourse(”intro to IT”); / / new f u n c t i o n a l i t y
stud.grad courses; / / new f u n c t i o n a l i t y
Possible Uses of Classes/Objects

encapsulating several pieces of non-homogeneous


information, e.g., as accumulator to reduce;

creating nested structures;

implementing a data structure nicely, by exposing only the


intended functionality;
Nested Structure
cl a s s Student {
name ; // a string
c o u r s e s ; / / an a r r a y o f s t r i n g s

c o n s t r u c t o r ( nm , c r s ) {
t h i s . name = nm ;
t h i s . courses = cr s ;
}
toString ( ) {
r e t u r n ” S t u d e n t : ” + t h i s . name+ ” t a k e s : ” + t h i s . c o u r s e s . t o S t r i n g ( ) ;
}
}

c l a s s Co u r s e {
name ; // a string
s t u d e n t s ; / / an a r r a y o f s t r i n g s

c o n s t r u c t o r ( nm , s t d s ) {
t h i s . name = nm ;
this . students = stds ;
}
toString ( ) {
r e t u r n ” Co u r s e : ” + t h i s . name+ ” i s t a ke n by : ” + t h i s . s t u d e n t s . t o S t r i n g ( ) ;
}
}

A student object consists of a name (string), and an array of taken courses (array
of strings).
A course object consists of a name (string), and an array of students taking the
course (array of string).
Nested Structure
cl a s s Student {
...
}

c l a s s Co u r s e {
...
}

let arr of studs = [ ] ;


a r r o f s t u d s . push ( new Student(’Hermione’, [’potions’, ’alchemy’]) ) ;
a r r o f s t u d s . push ( new Student(’Harry’, [’arithmancy’, ’charms’]) ) ;

a student object consists of a name (string), and an array of


taken courses, (array of strings);
a course object consists of a name (string), and an array of
students taking the course (array of string);
we may have an array of student objects (arr of studs);
Can we build an array of course objects that is consistent
with the array of students? This is your main task in the
exercise session.
Notes for Teacher: If Time Permits

Take a look at the third assignment;

Discuss the exercise session from last time, e.g., the


interaction of javascript code with the HTML graphical
interface in the case of the prime table;

Demonstrate the exercises for today, and maybe start


working on them.
Summary

Get comfortable with split and join, lots of tasks ends up


being manipulation of arrays and strings;
An object is a set of named values grouped together (using
braces);
Objects can be nested and put in arrays. Arrays can be put in
objects as well.
Classes, inheritance are useful tools in structuring your code
into manageable pieces.
Objects are mutable, so beware of mutations.
We use objects to:
I cleanly implement data structures;
I to put together pieces of non-homogeneous information;
I to create nested structures;

You might also like