SlideShare a Scribd company logo
Using Objects and Classes
Defining Simple Classes
Objects and Classes
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Table of Contents
1. Objects
2. Classes
3. Built in Classes
4. Defining Simple Classes
 Properties
 Methods
 Constructors
2
sli.do
#fund-csharp
Have a Question?
3
Objects and Classes
What is an Object? What is a Class?
Objects
 An object holds a set of named values
 E.g. birthday object holds day, month and year
 Creating a birthday object:
5
var birthday = new { Day = 22, Month = 6, Year = 1990 };
Birthday
Day = 22
Month = 6
Year = 1990 The new operator creates
a new object
var day = new DateTime(
2019, 2, 25);
Console.WriteLine(day);
Object
properties
Object
name
Create a new object
of type DateTime
Classes
 In programming, classes provide the structure for objects
 Act as template for objects of the same type
 Classes define:
 Data (properties), e.g. Day, Month, Year
 Actions (behaviour), e.g. AddDays(count),
Subtract(date)
 One class may have many instances (objects)
 Sample class: DateTime
 Sample objects: peterBirthday, mariaBirthday
6
Objects - Instances of Classes
 Creating the object of a defined class is
called instantiation
 The instance is the object itself, which is
created runtime
 All instances have common behaviour
7
DateTime date1 = new DateTime(2018, 5, 5);
DateTime date2 = new DateTime(2016, 3, 5);
DateTime date3 = new DateTime(2013, 12, 31);
Objects and Classes – Example
8
DateTime peterBirthday = new DateTime(1996, 11, 27);
DateTime mariaBirthday = new DateTime(1995, 6, 14);
Console.WriteLine("Peter's birth date: {0:d-MMM-yyyy}",
peterBirthday); // 27-Nov-1996
Console.WriteLine("Maria's birth date: {0:d-MMM-yyyy}",
mariaBirthday); // 14-Jun-1995
var mariaAfter18Months = mariaBirthday.AddMonths(18);
Console.WriteLine("Maria after 18 months: {0:d-MMM-yyyy}",
mariaAfter18Months); // 14-Dec-1996
TimeSpan ageDiff = peterBirthday.Subtract(mariaBirthday);
Console.WriteLine("Maria older than Peter by: {0} days",
ageDiff.Days); // 532 days
Classes vs. Objects
 Classes provide structure for
creating objects
 An object is a single
instance of a class
9
class
DateTime
Day: int
Month: int
Year: int
AddDays(…)
Subtract(…)
Class actions
(methods)
Class name
Class data
(properties)
object
peterBirthday
Day = 27
Month = 11
Year = 1996
Object
name
Object
data
 You are given a date in format day-month-year
 Calculate and print the day of week in English
Problem: Day of Week
10
18-04-2016 Monday 27-11-1996
string dateAsText = Console.ReadLine();
DateTime date = DateTime.ParseExact(dateAsText, "d-M-yyyy",
CultureInfo.InvariantCulture);
Console.WriteLine(date.DayOfWeek);
ParseExact(…) needs a
format string + culture
(locale)
Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
Wednesday
Using the Built-in API Classes
Math, Random, BigInteger, ...
 .NET Core provides thousands of ready-to-use classes
 Packaged into namespaces like System, System.Text,
System.Collections, System.Linq, System.Net, etc.
 Using static .NET class members:
 Using non-static .NET classes
Built-in API Classes in .NET Core
12
DateTime today = DateTime.Now;
double cosine = Math.Cos(Math.PI);
Random rnd = new Random();
int randomNumber = rnd.Next(1, 99);
 You are given a list of words
 Randomize their order and print each word at a separate line
Problem: Randomize Words
13
Note: The output is a sample. It
should always be different!
a b
b
a
PHP Java C#
Java
PHP
C#
Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
Solution: Randomize Words
14
string[] words = Console.ReadLine().Split(' ');
Random rnd = new Random();
for (int pos1 = 0; pos1 < words.Length; pos1++)
{
int pos2 = rnd.Next(words.Length);
// TODO: Swap words[pos1] with words[pos2]
}
Console.WriteLine(string.Join(Environment.NewLine, words));
Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
 Calculate n! (n factorial) for very big n (e.g. 1000)
Problem: Big Factorial
15
50
3041409320171337804361260816606476884437764156
8960512000000000000
5 120 10 3628800 12 479001600
88
1854826422573984391147968456455462843802209689
4939934668442158098688956218402819931910014124
4804501828416633516851200000000000000000000
Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
Solution: Big Factorial
16
using System.Numerics;
...
int n = int.Parse(Console.ReadLine());
BigInteger f = 1;
for (int i = 2; i <= n; i++)
f *= i;
Console.WriteLine(f);
Use the .NET API class
System.Numerics
.BigInteger
N!Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
Defining Classes
Creating Custom Classes
 Specification of a given type of objects from
the real-world
 Classes provide structure for describing
and creating objects
Defining Simple Classes
class Dice
{
…
}
Class name
Class body
Keyword
18
Naming Classes
 Use PascalCase naming
 Use descriptive nouns
 Avoid abbreviations (except widely known, e.g. URL,
HTTP, etc.)
19
class Dice { … }
class BankAccount { … }
class IntegerCalculator { … }
class TPMF { … }
class bankaccount { … }
class intcalc { … }
 Class is made up of state and behavior
 Properties store state
 Methods describe behaviour
Class Members
20
class Dice
{
public int Sides { get; set; }
public string Type { get; set; }
public void Roll() { }
}
Properties
Method
 A class can have many instances (objects)
Creating an Object
21
class Program
{
public static void Main()
{
Dice diceD6 = new Dice();
Dice diceD8 = new Dice();
}
}
Use the new
keyword
 Describe the characteristics of a given class
Properties
22
class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
The getter provides
access to the field
The setter provides
field change
 Store executable code (algorithm)
Methods
23
class Dice
{
public int Sides { get; set; }
public int Roll()
{
Random rnd = new Random();
return rnd.Next(1, Sides + 1);
}
}
 Special methods, executed during object creation
Constructors
24
class Dice
{
public int Sides { get; set; }
public Dice()
{
this.Sides = 6;
}
}
Overloading default
constructor
Constructor name is
the same as the name
of the class
 You can have multiple constructors in the same class
Constructors (2)
25
class Dice
{
public Dice() { }
public Dice(int sides)
{
this.Sides = sides;
}
p int Sides { get; set; }
}
class StartUp
{
public static void Main()
{
Dice dice1 = new Dice();
Dice dice2 = new Dice(7);
}
}
 Classes can define data (state) and operations (actions)
Class Operations
26
class Rectangle
{
public int Top { get; set; }
public int Left { get; set; }
public int Width { get; set; }
public int Height { get; set; }
int CalcArea()
{
return Width * Height;
}
Classes may hold
data (properties)
Classes may hold
operations
(methods)
Class Operations (2)
27
public int Bottom
{
get
{
return Top + Height;
}
}
public int Right
{
get
{
return Left + Width;
}
}
Calculated
property
Calculated
property
public bool IsInside(Rectangle r)
{
return (r.Left <= Left) && (r.Right >= Right) &&
(r.Top <= Top) && (r.Bottom >= Bottom);
}
Boolean
method
 …
 …
 …
Summary
28
 Objects
 Holds a set of named values
 Instance of a class
 Classes define templates for object
 Methods
 Constructors
 Properties
 https://softuni.bg/courses/technology-fundamentals 29
SoftUni Diamond Partners
30
SoftUni Organizational Partners
31
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
32
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
33
Ad

More Related Content

What's hot (20)

05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 
Basic c#
Basic c#Basic c#
Basic c#
kishore4268
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
Tushar Desarda
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
11. java methods
11. java methods11. java methods
11. java methods
M H Buddhika Ariyaratne
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
Raja Sekhar
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
Mayank Jain
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)Classes in c++ (OOP Presentation)
Classes in c++ (OOP Presentation)
Majid Saeed
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
SPF Getting Started - Console Program
SPF Getting Started - Console ProgramSPF Getting Started - Console Program
SPF Getting Started - Console Program
Hock Leng PUAH
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
Raja Sekhar
 

Similar to 11. Objects and Classes (20)

Object Oriented Programming - 5. Class & Object
Object Oriented Programming - 5. Class & ObjectObject Oriented Programming - 5. Class & Object
Object Oriented Programming - 5. Class & Object
AndiNurkholis1
 
Classes1
Classes1Classes1
Classes1
phanleson
 
Chap08
Chap08Chap08
Chap08
Terry Yoast
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
sdrhr
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
sidra tauseef
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
Mahmoud Ouf
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
Terry Yoast
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
SakhilejasonMsibi
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
Mahmoud Samir Fayed
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
Lab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx pptLab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
Sunil OS
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6
helpido9
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
Kuntal Bhowmick
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Object Oriented Programming - 5. Class & Object
Object Oriented Programming - 5. Class & ObjectObject Oriented Programming - 5. Class & Object
Object Oriented Programming - 5. Class & Object
AndiNurkholis1
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
sdrhr
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)C# (This keyword, Properties, Inheritance, Base Keyword)
C# (This keyword, Properties, Inheritance, Base Keyword)
Umar Farooq
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
Terry Yoast
 
The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202The Ring programming language version 1.8 book - Part 80 of 202
The Ring programming language version 1.8 book - Part 80 of 202
Mahmoud Samir Fayed
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
OOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming languageOOPS_Lab_Manual - programs using C++ programming language
OOPS_Lab_Manual - programs using C++ programming language
PreethaV16
 
Lab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx pptLab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
Sunil OS
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6Cis 355 i lab 3 of 6
Cis 355 i lab 3 of 6
helpido9
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methodsClass notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
Kuntal Bhowmick
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Ad

More from Intro C# Book (19)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro C# Book
 
17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
Intro C# Book
 
Ad

Recently uploaded (19)

Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 

11. Objects and Classes

  • 1. Using Objects and Classes Defining Simple Classes Objects and Classes Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. Table of Contents 1. Objects 2. Classes 3. Built in Classes 4. Defining Simple Classes  Properties  Methods  Constructors 2
  • 4. Objects and Classes What is an Object? What is a Class?
  • 5. Objects  An object holds a set of named values  E.g. birthday object holds day, month and year  Creating a birthday object: 5 var birthday = new { Day = 22, Month = 6, Year = 1990 }; Birthday Day = 22 Month = 6 Year = 1990 The new operator creates a new object var day = new DateTime( 2019, 2, 25); Console.WriteLine(day); Object properties Object name Create a new object of type DateTime
  • 6. Classes  In programming, classes provide the structure for objects  Act as template for objects of the same type  Classes define:  Data (properties), e.g. Day, Month, Year  Actions (behaviour), e.g. AddDays(count), Subtract(date)  One class may have many instances (objects)  Sample class: DateTime  Sample objects: peterBirthday, mariaBirthday 6
  • 7. Objects - Instances of Classes  Creating the object of a defined class is called instantiation  The instance is the object itself, which is created runtime  All instances have common behaviour 7 DateTime date1 = new DateTime(2018, 5, 5); DateTime date2 = new DateTime(2016, 3, 5); DateTime date3 = new DateTime(2013, 12, 31);
  • 8. Objects and Classes – Example 8 DateTime peterBirthday = new DateTime(1996, 11, 27); DateTime mariaBirthday = new DateTime(1995, 6, 14); Console.WriteLine("Peter's birth date: {0:d-MMM-yyyy}", peterBirthday); // 27-Nov-1996 Console.WriteLine("Maria's birth date: {0:d-MMM-yyyy}", mariaBirthday); // 14-Jun-1995 var mariaAfter18Months = mariaBirthday.AddMonths(18); Console.WriteLine("Maria after 18 months: {0:d-MMM-yyyy}", mariaAfter18Months); // 14-Dec-1996 TimeSpan ageDiff = peterBirthday.Subtract(mariaBirthday); Console.WriteLine("Maria older than Peter by: {0} days", ageDiff.Days); // 532 days
  • 9. Classes vs. Objects  Classes provide structure for creating objects  An object is a single instance of a class 9 class DateTime Day: int Month: int Year: int AddDays(…) Subtract(…) Class actions (methods) Class name Class data (properties) object peterBirthday Day = 27 Month = 11 Year = 1996 Object name Object data
  • 10.  You are given a date in format day-month-year  Calculate and print the day of week in English Problem: Day of Week 10 18-04-2016 Monday 27-11-1996 string dateAsText = Console.ReadLine(); DateTime date = DateTime.ParseExact(dateAsText, "d-M-yyyy", CultureInfo.InvariantCulture); Console.WriteLine(date.DayOfWeek); ParseExact(…) needs a format string + culture (locale) Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab Wednesday
  • 11. Using the Built-in API Classes Math, Random, BigInteger, ...
  • 12.  .NET Core provides thousands of ready-to-use classes  Packaged into namespaces like System, System.Text, System.Collections, System.Linq, System.Net, etc.  Using static .NET class members:  Using non-static .NET classes Built-in API Classes in .NET Core 12 DateTime today = DateTime.Now; double cosine = Math.Cos(Math.PI); Random rnd = new Random(); int randomNumber = rnd.Next(1, 99);
  • 13.  You are given a list of words  Randomize their order and print each word at a separate line Problem: Randomize Words 13 Note: The output is a sample. It should always be different! a b b a PHP Java C# Java PHP C# Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
  • 14. Solution: Randomize Words 14 string[] words = Console.ReadLine().Split(' '); Random rnd = new Random(); for (int pos1 = 0; pos1 < words.Length; pos1++) { int pos2 = rnd.Next(words.Length); // TODO: Swap words[pos1] with words[pos2] } Console.WriteLine(string.Join(Environment.NewLine, words)); Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
  • 15.  Calculate n! (n factorial) for very big n (e.g. 1000) Problem: Big Factorial 15 50 3041409320171337804361260816606476884437764156 8960512000000000000 5 120 10 3628800 12 479001600 88 1854826422573984391147968456455462843802209689 4939934668442158098688956218402819931910014124 4804501828416633516851200000000000000000000 Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
  • 16. Solution: Big Factorial 16 using System.Numerics; ... int n = int.Parse(Console.ReadLine()); BigInteger f = 1; for (int i = 2; i <= n; i++) f *= i; Console.WriteLine(f); Use the .NET API class System.Numerics .BigInteger N!Check your solution here: https://judge.softuni.bg/Contests/1214/Objects-and-Classes-Lab
  • 18.  Specification of a given type of objects from the real-world  Classes provide structure for describing and creating objects Defining Simple Classes class Dice { … } Class name Class body Keyword 18
  • 19. Naming Classes  Use PascalCase naming  Use descriptive nouns  Avoid abbreviations (except widely known, e.g. URL, HTTP, etc.) 19 class Dice { … } class BankAccount { … } class IntegerCalculator { … } class TPMF { … } class bankaccount { … } class intcalc { … }
  • 20.  Class is made up of state and behavior  Properties store state  Methods describe behaviour Class Members 20 class Dice { public int Sides { get; set; } public string Type { get; set; } public void Roll() { } } Properties Method
  • 21.  A class can have many instances (objects) Creating an Object 21 class Program { public static void Main() { Dice diceD6 = new Dice(); Dice diceD8 = new Dice(); } } Use the new keyword
  • 22.  Describe the characteristics of a given class Properties 22 class Student { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } } The getter provides access to the field The setter provides field change
  • 23.  Store executable code (algorithm) Methods 23 class Dice { public int Sides { get; set; } public int Roll() { Random rnd = new Random(); return rnd.Next(1, Sides + 1); } }
  • 24.  Special methods, executed during object creation Constructors 24 class Dice { public int Sides { get; set; } public Dice() { this.Sides = 6; } } Overloading default constructor Constructor name is the same as the name of the class
  • 25.  You can have multiple constructors in the same class Constructors (2) 25 class Dice { public Dice() { } public Dice(int sides) { this.Sides = sides; } p int Sides { get; set; } } class StartUp { public static void Main() { Dice dice1 = new Dice(); Dice dice2 = new Dice(7); } }
  • 26.  Classes can define data (state) and operations (actions) Class Operations 26 class Rectangle { public int Top { get; set; } public int Left { get; set; } public int Width { get; set; } public int Height { get; set; } int CalcArea() { return Width * Height; } Classes may hold data (properties) Classes may hold operations (methods)
  • 27. Class Operations (2) 27 public int Bottom { get { return Top + Height; } } public int Right { get { return Left + Width; } } Calculated property Calculated property public bool IsInside(Rectangle r) { return (r.Left <= Left) && (r.Right >= Right) && (r.Top <= Top) && (r.Bottom >= Bottom); } Boolean method
  • 28.  …  …  … Summary 28  Objects  Holds a set of named values  Instance of a class  Classes define templates for object  Methods  Constructors  Properties
  • 32.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni) 32
  • 33.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 33