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
 Fields
 Constructors
 Methods
sli.do
#fund-java
Have a Question?
Objects and Classes
Objects
 An object holds a set of named values
 E.g. birthday object holds day, month and year
 Creating a birthday object:
5
Birthday
day = 27
month = 11
year = 1996
LocalDate birthday =
LocalDate.of(2018, 5, 5);
System.out.println(birthday);
Create a new object of
type LocalDate
Object
fields
Object
name
Classes
 In programming classes provide the structure for objects
 Act as a blueprint for objects of the same type
 Classes define:
 Fields (private variables), e.g. day, month, year
 Getters/Setters, e.g. getDay, setMonth, getYear
 Actions (behavior), e.g. plusDays(count),
subtract(date)
 Typically a class has multiple instances (objects)
 Sample class: LocalDate
 Sample objects: birthdayPeter, birthdayMaria
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
LocalDate date1 = LocalDate.of(2018, 5, 5);
LocalDate date2 = LocalDate.of(2016, 3, 5);
LocalDate date3 = LocalDate.of(2013, 3, 2);
Classes vs. Objects
 Classes provide structure for
creating objects
 An object is a single
instance of a class
8
class
LocalDate
day: int
month: int
year: int
plusDays(…)
minusDays(…)
Class actions
(methods)
Class name
Class fields
object
birthdayPeter
day = 27
month = 11
year = 1996
Object
name
Object
data
Using the Built-In API Classes
Math, Random, BigInteger ...
 Java provides ready-to-use classes:
 Organized inside Packages like:
java.util.Scanner, java.utils.List, etc.
 Using static class members:
 Using non-static Java classes:
Built-In API Classes in Java
10
LocalDateTime today = LocalDateTime.now();
double cosine = Math.cos(Math.PI);
Random rnd = new Random();
int randomNumber = rnd.nextInt(99);
 You are given a list of words
 Randomize their order and print each word on a separate line
Problem: Randomize Words
11Check your solution here: https://judge.softuni.bg/Contests/1319/
Note: the output is a sample.
It should always be different!
a b
b
a
PHP Java C#
Java
PHP
C#
Solution: Randomize Words
12
Scanner sc = new Scanner(System.in);
String[] words = sc.nextLine().split(" ");
Random rnd = new Random();
for (int pos1 = 0; pos1 < words.length; pos1++) {
int pos2 = rnd.nextInt(words.length);
//TODO: Swap words[pos1] with words[pos2]
}
System.out.println(String.join(
System.lineSeparator(), words));
Check your solution here: https://judge.softuni.bg/Contests/1319/
 Calculate n! (n factorial) for very big n (e.g. 1000)
Problem: Big Factorial
13
50
3041409320171337804361260816606476884437764156
8960512000000000000
5 120 10 3628800 12 479001600
88
1854826422573984391147968456455462843802209689
4939934668442158098688956218402819931910014124
4804501828416633516851200000000000000000000
Check your solution here: https://judge.softuni.bg/Contests/1319/
Solution: Big Factorial
14
import java.math.BigInteger;
...
int n = Integer.parseInt(sc.nextLine());
BigInteger f = new BigInteger(String.valueOf(1));
for (int i = 1; i <= n; i++) {
f = f.multiply(BigInteger
.valueOf(Integer.parseInt(String.valueOf(i))));
}
System.out.println(f);
Use the
java.math.BigInteger
N!
Check your solution here: https://judge.softuni.bg/Contests/1319/
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
16
class Dice {
…
}
Class name
Class body
Keyword
Naming Classes
 Use PascalCase naming
 Use descriptive nouns
 Avoid abbreviations (except widely known, e.g. URL,
HTTP, etc.)
17
class Dice { … }
class BankAccount { … }
class IntegerCalculator { … }
class TPMF { … }
class bankaccount { … }
class intcalc { … }
 Class is made up of state and behavior
 Fields store values
 Methods describe behaviour
Class Members
18
class Dice {
private int sides;
public void roll() { … }
}
Field
Method
 Store executable code (algorithm)
Methods
19
class Dice {
public int sides;
public int roll() {
Random rnd = new Random();
int sides = rnd.nextInt(this.sides + 1);
return sides;
}
}
Getters and Setters
20
class Dice {
. . .
public int getSides() { return this.sides; }
public void setSides(int sides) {
this.sides = sides;
}
public String getType() { return this.type; }
public void setType(String type) {
this.type = type;
}
}
Getters & Setters
 A class can have many instances (objects)
Creating an Object
21
class Program {
public static void main(String[] args) {
Dice diceD6 = new Dice();
Dice diceD8 = new Dice();
}
}
Use the new
keyword
Variable stores a
reference
 Special methods, executed during object creation
Constructors
22
class Dice {
public int sides;
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)
23
class Dice {
public int sides;
public Dice() { }
public Dice(int sides) {
this.sides = sides;
}
}
class StartUp {
public static void main(String[] args) {
Dice dice1 = new Dice();
Dice dice2 = new Dice(7);
}
}
 Read students until you receive "end" in the following format:
 "{firstName} {lastName} {age} {hometown}"
 Define a class Student, which holds the needed information
 If you receive a student which already exists (matching
firstName and lastName), overwrite the information
 After the end command, you will receive a city name
 Print students which are from the given city in the format:
"{firstName} {lastName} is {age} years old."
Problem: Students
24
Solution: Students (1)
25
public Student(String firstName, String lastName,
int age, String city){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.city = city;
// TODO: Implement Getters and Setters
}
Solution: Students (2)
26
List<Student> students = new ArrayList<>();
String line;
while (!line.equals("end")) {
// TODO: Extract firstName, lastName, age, city from the input
Student existingStudent = getStudent(students, firstName, lastName);
if(existingStudent != null) {
existingStudent.setAge(age);
existingStudent.setCity(city);
} else {
Student student = new Student(firstName, lastName, age, city);
students.add(student);
}
line = sc.nextLine();
}
Solution: Students (3)
27
static Student getStudent(List<Student> students, String firstName,
String lastName) {
for (Student student : students){
if(student.getFirstName().equals(firstName)
&& student.getLastName().equals(lastName))
return student;
}
return null;
}
Live Exercises
 …
 …
 …
Summary
 Classes define templates for object
 Fields
 Constructors
 Methods
 Objects
 Hold a set of named values
 Instance of a class
 https://softuni.bg/courses/programming-fundamentals
SoftUni Diamond Partners
SoftUni Organizational Partners
 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)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
34

More Related Content

What's hot (20)

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Php oop presentation
Php   oop presentationPhp   oop presentation
Php oop presentation
Mutinda Boniface
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Christian Schneider
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class library
Prem Kumar Badri
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
Sunil OS
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
Java Stack Data Structure.pptx
Java Stack Data Structure.pptxJava Stack Data Structure.pptx
Java Stack Data Structure.pptx
vishal choudhary
 
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Serial Killer - Silently Pwning your Java Endpoints // OWASP BeNeLux Day 2016
Christian Schneider
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
C# Framework class library
C# Framework class libraryC# Framework class library
C# Framework class library
Prem Kumar Badri
 
Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013Domain Driven Design with the F# type System -- NDC London 2013
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 

Similar to 11. Java Objects and classes (20)

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
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
Intro C# Book
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
Muhammad Fayyaz
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
PawanMM
 
Lecture3.pdf
Lecture3.pdfLecture3.pdf
Lecture3.pdf
SakhilejasonMsibi
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
Lab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx pptLab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
Classes1
Classes1Classes1
Classes1
phanleson
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
New C# features
New C# featuresNew C# features
New C# features
Alexej Sommer
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
Jeop game-final-review
Jeop game-final-reviewJeop game-final-review
Jeop game-final-review
Stephanie Weirich
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
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
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
Intro C# Book
 
Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
PawanMM
 
Lecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptxLecture_4_Static_variables_and_Methods.pptx
Lecture_4_Static_variables_and_Methods.pptx
IkaDeviPerwitasari1
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
Lab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx pptLab4-Software-Construction-BSSE5.pptx ppt
Lab4-Software-Construction-BSSE5.pptx ppt
MuhammadAbubakar114879
 
OOP with Java - Continued
OOP with Java - Continued OOP with Java - Continued
OOP with Java - Continued
Hitesh-Java
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Ad

More from Intro C# Book (20)

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.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
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
 
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
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
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
 
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
 
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
 
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
 
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
 
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.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
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
 
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
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
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
 
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
 
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
 
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
 
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 (20)

What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
treyka
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 
MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
Timeline Infographics Para utilização diária
Timeline Infographics Para utilização diáriaTimeline Infographics Para utilização diária
Timeline Infographics Para utilização diária
meslellis
 
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
it.com Domains
 
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
Taqyea
 
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptxInter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
secretarysocom
 
PPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programmePPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programme
AbhimanShastry
 
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx
islamicknowledge5224
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
Internet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptxInternet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptx
cshumerabashir
 
Google_Cloud_Computing_Fundamentals.pptx
Google_Cloud_Computing_Fundamentals.pptxGoogle_Cloud_Computing_Fundamentals.pptx
Google_Cloud_Computing_Fundamentals.pptx
ektadangwal2005
 
rosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptxrosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptx
sirbabu778
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM HallucinationsCBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
Jason Packer
 
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
What to Expect When Hiring Shopify Development Services_ A Technical Walkthro...
CartCoders
 
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
Darley - BSides Nairobi (2025-06-07) Epochalypse 2038 - Time is Not on Our Si...
treyka
 
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdfPredicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Predicting Site Quality Google Patent US9767157B2 - Behzad Hussain.pdf
Behzad Hussain
 
MOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary detailsMOBILE PHONE DATA presentation with all necessary details
MOBILE PHONE DATA presentation with all necessary details
benamorraj
 
Timeline Infographics Para utilização diária
Timeline Infographics Para utilização diáriaTimeline Infographics Para utilização diária
Timeline Infographics Para utilização diária
meslellis
 
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...The it.com Domains Brand Book for registrars, domain resellers and hosting co...
The it.com Domains Brand Book for registrars, domain resellers and hosting co...
it.com Domains
 
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
最新版英国北安普顿大学毕业证(UoN毕业证书)原版定制
Taqyea
 
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptxInter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
Inter-Mirifica-Navigating-Media-in-the-Modern-World.pptx
secretarysocom
 
PPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programmePPT 18.03.2023.pptx for i smart programme
PPT 18.03.2023.pptx for i smart programme
AbhimanShastry
 
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animationUV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
UV_Unwrapping_Lecture_with_Figures.pptx presentation for lecture of animation
17218
 
In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...In order to install and use the device software, your computer must meet the ...
In order to install and use the device software, your computer must meet the ...
raguclc
 
simple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptxsimple-presentationtestingdocument2007.pptx
simple-presentationtestingdocument2007.pptx
ashokjayapal
 
Internet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet SystemInternet & Protocols : A Blueprint of the Internet System
Internet & Protocols : A Blueprint of the Internet System
cpnabil59
 
3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx3D Graphics an introduction and details .pptx
3D Graphics an introduction and details .pptx
islamicknowledge5224
 
Cloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptxCloud Computing - iCloud by Hamza Anwaar .pptx
Cloud Computing - iCloud by Hamza Anwaar .pptx
islamicknowledge5224
 
Internet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptxInternet_of_Things_Presentation_by-Humera.pptx
Internet_of_Things_Presentation_by-Humera.pptx
cshumerabashir
 
Google_Cloud_Computing_Fundamentals.pptx
Google_Cloud_Computing_Fundamentals.pptxGoogle_Cloud_Computing_Fundamentals.pptx
Google_Cloud_Computing_Fundamentals.pptx
ektadangwal2005
 
rosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptxrosoft PowcgnggerPoint Presentation.pptx
rosoft PowcgnggerPoint Presentation.pptx
sirbabu778
 
3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen3 years of Quarkus in production, what have we learned - Devoxx Polen
3 years of Quarkus in production, what have we learned - Devoxx Polen
Jago de Vreede
 
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM HallucinationsCBUSDAW - Ash Lewis - Reducing LLM Hallucinations
CBUSDAW - Ash Lewis - Reducing LLM Hallucinations
Jason Packer
 

11. Java 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  Fields  Constructors  Methods
  • 5. Objects  An object holds a set of named values  E.g. birthday object holds day, month and year  Creating a birthday object: 5 Birthday day = 27 month = 11 year = 1996 LocalDate birthday = LocalDate.of(2018, 5, 5); System.out.println(birthday); Create a new object of type LocalDate Object fields Object name
  • 6. Classes  In programming classes provide the structure for objects  Act as a blueprint for objects of the same type  Classes define:  Fields (private variables), e.g. day, month, year  Getters/Setters, e.g. getDay, setMonth, getYear  Actions (behavior), e.g. plusDays(count), subtract(date)  Typically a class has multiple instances (objects)  Sample class: LocalDate  Sample objects: birthdayPeter, birthdayMaria 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 LocalDate date1 = LocalDate.of(2018, 5, 5); LocalDate date2 = LocalDate.of(2016, 3, 5); LocalDate date3 = LocalDate.of(2013, 3, 2);
  • 8. Classes vs. Objects  Classes provide structure for creating objects  An object is a single instance of a class 8 class LocalDate day: int month: int year: int plusDays(…) minusDays(…) Class actions (methods) Class name Class fields object birthdayPeter day = 27 month = 11 year = 1996 Object name Object data
  • 9. Using the Built-In API Classes Math, Random, BigInteger ...
  • 10.  Java provides ready-to-use classes:  Organized inside Packages like: java.util.Scanner, java.utils.List, etc.  Using static class members:  Using non-static Java classes: Built-In API Classes in Java 10 LocalDateTime today = LocalDateTime.now(); double cosine = Math.cos(Math.PI); Random rnd = new Random(); int randomNumber = rnd.nextInt(99);
  • 11.  You are given a list of words  Randomize their order and print each word on a separate line Problem: Randomize Words 11Check your solution here: https://judge.softuni.bg/Contests/1319/ Note: the output is a sample. It should always be different! a b b a PHP Java C# Java PHP C#
  • 12. Solution: Randomize Words 12 Scanner sc = new Scanner(System.in); String[] words = sc.nextLine().split(" "); Random rnd = new Random(); for (int pos1 = 0; pos1 < words.length; pos1++) { int pos2 = rnd.nextInt(words.length); //TODO: Swap words[pos1] with words[pos2] } System.out.println(String.join( System.lineSeparator(), words)); Check your solution here: https://judge.softuni.bg/Contests/1319/
  • 13.  Calculate n! (n factorial) for very big n (e.g. 1000) Problem: Big Factorial 13 50 3041409320171337804361260816606476884437764156 8960512000000000000 5 120 10 3628800 12 479001600 88 1854826422573984391147968456455462843802209689 4939934668442158098688956218402819931910014124 4804501828416633516851200000000000000000000 Check your solution here: https://judge.softuni.bg/Contests/1319/
  • 14. Solution: Big Factorial 14 import java.math.BigInteger; ... int n = Integer.parseInt(sc.nextLine()); BigInteger f = new BigInteger(String.valueOf(1)); for (int i = 1; i <= n; i++) { f = f.multiply(BigInteger .valueOf(Integer.parseInt(String.valueOf(i)))); } System.out.println(f); Use the java.math.BigInteger N! Check your solution here: https://judge.softuni.bg/Contests/1319/
  • 16.  Specification of a given type of objects from the real-world  Classes provide structure for describing and creating objects Defining Simple Classes 16 class Dice { … } Class name Class body Keyword
  • 17. Naming Classes  Use PascalCase naming  Use descriptive nouns  Avoid abbreviations (except widely known, e.g. URL, HTTP, etc.) 17 class Dice { … } class BankAccount { … } class IntegerCalculator { … } class TPMF { … } class bankaccount { … } class intcalc { … }
  • 18.  Class is made up of state and behavior  Fields store values  Methods describe behaviour Class Members 18 class Dice { private int sides; public void roll() { … } } Field Method
  • 19.  Store executable code (algorithm) Methods 19 class Dice { public int sides; public int roll() { Random rnd = new Random(); int sides = rnd.nextInt(this.sides + 1); return sides; } }
  • 20. Getters and Setters 20 class Dice { . . . public int getSides() { return this.sides; } public void setSides(int sides) { this.sides = sides; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } } Getters & Setters
  • 21.  A class can have many instances (objects) Creating an Object 21 class Program { public static void main(String[] args) { Dice diceD6 = new Dice(); Dice diceD8 = new Dice(); } } Use the new keyword Variable stores a reference
  • 22.  Special methods, executed during object creation Constructors 22 class Dice { public int sides; public Dice() { this.sides = 6; } } Overloading default constructor Constructor name is the same as the name of the class
  • 23.  You can have multiple constructors in the same class Constructors (2) 23 class Dice { public int sides; public Dice() { } public Dice(int sides) { this.sides = sides; } } class StartUp { public static void main(String[] args) { Dice dice1 = new Dice(); Dice dice2 = new Dice(7); } }
  • 24.  Read students until you receive "end" in the following format:  "{firstName} {lastName} {age} {hometown}"  Define a class Student, which holds the needed information  If you receive a student which already exists (matching firstName and lastName), overwrite the information  After the end command, you will receive a city name  Print students which are from the given city in the format: "{firstName} {lastName} is {age} years old." Problem: Students 24
  • 25. Solution: Students (1) 25 public Student(String firstName, String lastName, int age, String city){ this.firstName = firstName; this.lastName = lastName; this.age = age; this.city = city; // TODO: Implement Getters and Setters }
  • 26. Solution: Students (2) 26 List<Student> students = new ArrayList<>(); String line; while (!line.equals("end")) { // TODO: Extract firstName, lastName, age, city from the input Student existingStudent = getStudent(students, firstName, lastName); if(existingStudent != null) { existingStudent.setAge(age); existingStudent.setCity(city); } else { Student student = new Student(firstName, lastName, age, city); students.add(student); } line = sc.nextLine(); }
  • 27. Solution: Students (3) 27 static Student getStudent(List<Student> students, String firstName, String lastName) { for (Student student : students){ if(student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) return student; } return null; }
  • 29.  …  …  … Summary  Classes define templates for object  Fields  Constructors  Methods  Objects  Hold a set of named values  Instance of a class
  • 33.  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)
  • 34.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 34