Objects and Classes
Using Objects and Classes
Defining Simple Classes
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. Objects
2. Classes
3. Built in Classes
4. Defining Simple Classes
Fields
Constructors
Methods
Have a Question?
sli.do
#fund-java
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:
Birthday Object LocalDate birthday =
name
day = 27 LocalDate.of(2018, 5, 5);
System.out.println(birthday);
month = 11 Object
fields Create a new object of
year = 1996
type LocalDate
5
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
LocalDate date1 = LocalDate.of(2018, 5, 5);
LocalDate date2 = LocalDate.of(2016, 3, 5);
LocalDate date3 = LocalDate.of(2013, 3, 2);
7
Classes vs. Objects
Classes provide structure for An object is a single
creating objects instance of a class
class object Object
LocalDate Class name
birthdayPeter name
day: int day = 27
month: int Class fields month = 11 Object
year: int data
year = 1996
plusDays(…) Class actions
minusDays(…) (methods)
8
Using the Built-In API Classes
Math, Random, BigInteger ...
Built-In API Classes in Java
Java provides ready-to-use classes:
Organized inside Packages like:
java.util.Scanner, java.utils.List, etc.
Using static class members:
LocalDateTime today = LocalDateTime.now();
double cosine = Math.cos(Math.PI);
Using non-static Java classes:
Random rnd = new Random();
int randomNumber = rnd.nextInt(99); 10
Problem: Randomize Words
You are given a list of words
Randomize their order and print each word on a separate line
a b PHP Java C#
b Java
a PHP
C#
Note: the output is a sample.
It should always be different!
Check your solution here: https://judge.softuni.bg/Contests/1319/ 11
Solution: Randomize Words
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/ 12
Problem: Big Factorial
Calculate n! (n factorial) for very big n (e.g. 1000)
5 120 10 3628800 12 479001600
3041409320171337804361260816606476884437764156
50
8960512000000000000
1854826422573984391147968456455462843802209689
88 4939934668442158098688956218402819931910014124
4804501828416633516851200000000000000000000
Check your solution here: https://judge.softuni.bg/Contests/1319/ 13
Solution: Big Factorial
import java.math.BigInteger; Use the
... 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
N!
.valueOf(Integer.parseInt(String.valueOf(i))));
}
System.out.println(f);
Check your solution here: https://judge.softuni.bg/Contests/1319/ 14
Defining Classes
Creating Custom Classes
Defining Simple Classes
Specification of a given type of objects
from the real-world
Classes provide structure for describing
and creating objects
Class name
Keyword
class Dice {
… Class body
}
16
Naming Classes
Use PascalCase naming
Use descriptive nouns
Avoid abbreviations (except widely known, e.g. URL,
HTTP, etc.)
class Dice { … }
class BankAccount { … }
class IntegerCalculator { … }
class TPMF { … }
class bankaccount { … }
class intcalc { … } 17
Class Members
Class is made up of state and behavior
Fields store values
Methods describe behaviour
class Dice {
private int sides; Field
public void roll() { … } Method
}
18
Methods
Store executable code (algorithm)
class Dice {
public int sides;
public int roll() {
Random rnd = new Random();
int sides = rnd.nextInt(this.sides + 1);
return sides;
}
}
19
Getters and Setters
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
} 20
Creating an Object
A class can have many instances (objects)
class Program {
public static void main(String[] args) {
Dice diceD6 = new Dice();
Dice diceD8 = new Dice();
} Use the new
} keyword
Variable stores a
reference
21
Constructors
Special methods, executed during object creation
class Dice {
public int sides;
Constructor name is
public Dice() { the same as the name
this.sides = 6; of the class
}
Overloading default
} constructor
22
Constructors (2)
You can have multiple constructors in the same class
class Dice { class StartUp {
public int sides; public static void main(String[] args) {
public Dice() { } Dice dice1 = new Dice();
public Dice(int sides) { Dice dice2 = new Dice(7);
this.sides = sides; }
} }
}
23
Problem: Students
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."
24
Solution: Students (1)
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
}
25
Solution: Students (2)
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();
}
26
Solution: Students (3)
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;
}
27
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
Trainings @ Software University (SoftUni)
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
License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
34