SlideShare a Scribd company logo
Classes, Fields, Constructors, Methods
Defining Classes
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1. Defining Simple Classes
2. Fields
3. Methods
4. Constructors, Keyword this
5. Static Members
Table of Contents
2
sli.do
#java-advanced
Have a Question?
Defining Classes
 Specification of a given type of objects
from the real-world
 Classes provide structure for describing
and creating objects
Defining Simple Classes
5
class Car {
…
}
Class name
Class body
Keyword
Naming Classes
 Use PascalCase naming
 Use descriptive nouns
 Avoid ambiguous names
6
class Dice { … }
class BankAccount { … }
class IntegerCalculator { … }
class TPMF { … }
class bankaccount { … }
class numcalc { … }
Class Members
7
 Class is made up of state and behavior
 Fields store state
 Methods describe behaviour
class Car {
String make;
String model;
void start(){ … }
}
Fields
Method
class Dog {
int age;
String type;
void bark(){ … }
}
Fields
Method
Creating an Object
8
 A class can have many instances (objects)
class Program {
public static void main()
{
Car firstCar = new Car();
Car secondCar = new Car();
}
}
Variable stores a
reference
Use the new keyword
 Declaring a variable creates a reference in the stack
 The new keyword allocates memory on the heap
Object Reference
9
Car car = new Car();
HEAPSTACK
diceD6
(1540e19d)
obj
type = null
sides = 0
Classes vs. Objects
10
 Classes provide structure for describing and creating objects
 An object is a single instance of a class
Dice (Class)
D6 Dice
(Object)
Class Data
Storing Data Inside a Class
Fields
12
public class Car {
private String make;
private int year;
public Person owner;
…
}
Fields can be of any
type
 Class fields have access modifiers, type and name
type
access modifier
name
 Create a class Car
 Ensure proper naming!
Problem: Define Car Class
13
Car
+make:String
+model:String
+horsePower:int
(no actions)
Class name
Class fields
Class methods
Solution: Define Car Class
14
public class Car {
String make;
String model;
int horsePower;
}
 Classes and class members have modifiers
 Modifiers define visibility
Access Modifiers
15
public class Car {
private String make;
private String model;
}
Class modifier
Member modifier
Fields should always
be private!
Methods
Defining a Class Behaviour
 Store executable code (algorithm) that manipulate state
Methods
17
class Car {
private int horsePower;
public void increaseHP(int value) {
horsePower += value;
}
}
 Used to create accessors and mutators (getters and setters)
Getters and Setters
18
class Car {
private int horsePower;
public int getHorsePower() {
return this.horsePower;
}
public void setHorsePower(int horsePower) {
this.horsePower = horsePower;
}
}
Field is hidden
Getter provides
access to field
Setter provide field change
this points to the
current instance
 Keyword this
 Prevent field hiding
 Refers to a current object
Getters and Setters
19
private int horsePower;
public void setSides(int horsePower) {
this.horsePower = horsePower;
}
public void setSidesNotWorking(int horsePower) {
horsePower = horsePower;
}
 Create a class Car
Problem: Car Info
20
Car
-make:String
…
+setMake():void
+getMake():String
…
+carInfo():String
+ == public
- == private
return type
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Solution: Car Info
21
public class Car {
private String make;
private String model;
private int horsePower;
public void setMake(String make) { this.make = make; }
public String getMake() { return this.make; }
public String carInfo() {
return String.format("The car is: %s %s - %d HP.",
this.make, this.model, this.horsePower);
}
//TODO: Create the other Getters and Setters
}
//TODO: Test the program
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Constructors
Object Initialization
 Special methods, executed during object creation
 The only one way to call a constructor in Java is
through the keyword new
Constructors
23
public class Car {
private String make;
public Car() {
this.make = "BMW";
}
}
Overloading default
constructor
 Special methods, executed during object creation
Constructors (1)
24
class Car {
private String make;
…
public Car() {
this.make = "unknown";
…
}
}
Overloading default
constructor
 You can have multiple constructors in the same class
Constructors (2)
25
public class Car {
private int horsePower; private String make;
public Car(String make) {
this.make = make;
}
public Car(String make, int horsePower) {
this.make = make;
this.horsePower = horsePower;
}
}
Constructor with all
parameters
Constructor with one
parameter
 Constructors set object's initial state
Object Initial State
26
public class Car {
String make;
List<Part> parts;
public Car(String make) {
this.make = make;
this.parts = new ArrayList<>();
}
}
Always ensure
correct state
 Constructors can call each other
Constructor Chaining
27
class Car {
private String make;
private int horsePower;
public Car(String make, int horsePower) {
this(make);
this.horsePower = horsePower;
}
public Car(String make) {
this.make = make;
}
}
 Create a class Car
Problem: Constructors
28
Car
-make:String
-model:String
-horsePower:int
+Car(String make)
+Car(String make, String model,
int horsePower)
+carInfo():String
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Solution: Constructors
29
public Car(String make) {
this.make = make;
this.model = "unknown";
this.horsePower = -1;
}
public Car(String make, String model, int horsePower) {
this(make);
this.model = model;
this.horsePower = horsePower;
}
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Static Members
Members Common for the Class
 Access static members through the class name
 Static members are shared class-wide
 You don't need an instance
Static Members
31
class Program {
public static void main(String[] args) {
BankAccount.setInterestRate(2.2);
}
}
Sets the rate for all
bank accounts
Static Members
32
class BankAccount {
private static int accountsCount;
private static double interestRate;
public BankAccount() {
accountsCount++;
}
public static void setInterestRate(double rate) {
interestRate = rate;
}
}
 Create a class BankAccount
 Support commands:
 Create
 Deposit {ID} {Amount}
 SetInterest {Interest}
 GetInterest {ID} {Years}
 End
Problem: Bank Account
33
BankAccount
-id:int (starts from 1)
-balance:double
-interestRate:double (default: 0.02)
+setInterest(double interest):void
+getId():int
+getInterest(int years):double
+deposit(double amount):void
Create
Deposit 1 20
GetInterest 1 10
End
Account ID1 Created
Deposited 20 to ID1
4.00
(20 * 0.02) * 10
underline ==
static
Solution: Bank Account
34
public class BankAccount {
private final static double DEFAULT_INTEREST = 0.02;
private static double rate = DEFAULT_INTEREST;
private static int bankAccountsCount;
private int id;
private double balance;
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Solution: Bank Account (2)
35
public BankAccount() {
this.id = ++bankAccountsCount;
}
public static void setInterest(double interest) {
rate = interest;
}
// TODO: int getId()
// TODO: double getInterest(int years)
// TODO: void deposit(double amount)
// TODO: override toString()
}
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
Solution: Bank Account (2)
36
HashMap<Integer, BankAccount> bankAccounts = new HashMap<>();
while (!command.equals("End")) {
//TODO: Get command args
switch (cmdType) {
case "Create": // TODO
case "Deposit": // TODO
case "SetInterest": // TODO
case "GetInterest": // TODO
}
//TODO: Read command
}
Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
 …
 …
 …
Summary
37
 Classes define specific structure for objects
 Objects are particular instances of a class
 Classes define fields, methods, constructors
and other members
 Constructors are invoked when creating new
class instances
 Constructors initialize the object's
initial state
 https://softuni.bg/modules/59/java-advanced
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
42
Ad

More Related Content

What's hot (20)

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
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
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
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
 
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
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
Basic c#
Basic c#Basic c#
Basic c#
kishore4268
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
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 Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
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
 
Java ppt Gandhi Ravi ([email protected])
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi ([email protected])
Gandhi Ravi
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
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
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
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
 
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
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
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 Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
mohamedsamyali
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
mohamedsamyali
 
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
 

Similar to 14. Java defining classes (20)

Unit4_2.pdf
Unit4_2.pdfUnit4_2.pdf
Unit4_2.pdf
ElakkiyaE8
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Ch03
Ch03Ch03
Ch03
ojac wdaj
 
Ch03
Ch03Ch03
Ch03
Gus Sandoval
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
Aram Mohammed
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
Kamal Acharya
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
CS 32 Final Review Fall 2024 ucla school data
CS 32 Final Review Fall 2024 ucla school dataCS 32 Final Review Fall 2024 ucla school data
CS 32 Final Review Fall 2024 ucla school data
kimberlyjcui
 
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
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
Rays Technologies
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
MuhammadHuzaifa981023
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
Jussi Pohjolainen
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
Abed Bukhari
 
Chapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part IChapter 4 - Defining Your Own Classes - Part I
Chapter 4 - Defining Your Own Classes - Part I
Eduardo Bergavera
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
Vince Vo
 
CS 32 Final Review Fall 2024 ucla school data
CS 32 Final Review Fall 2024 ucla school dataCS 32 Final Review Fall 2024 ucla school data
CS 32 Final Review Fall 2024 ucla school data
kimberlyjcui
 
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
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz Kosarzycki
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx05 Object Oriented Concept Presentation.pptx
05 Object Oriented Concept Presentation.pptx
ToranSahu18
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
Seok-joon Yun
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Ad

More from Intro C# Book (16)

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
 
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
 
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
 
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
 
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
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
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
 
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
 
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
 
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
 
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
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
Ad

Recently uploaded (19)

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
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
(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
 
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
 
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
 
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
 
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
 
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
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
(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
 
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
 
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
 
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
 
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
 
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
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 
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
 

14. Java defining classes

  • 1. Classes, Fields, Constructors, Methods Defining Classes Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. 1. Defining Simple Classes 2. Fields 3. Methods 4. Constructors, Keyword this 5. Static Members Table of Contents 2
  • 5.  Specification of a given type of objects from the real-world  Classes provide structure for describing and creating objects Defining Simple Classes 5 class Car { … } Class name Class body Keyword
  • 6. Naming Classes  Use PascalCase naming  Use descriptive nouns  Avoid ambiguous names 6 class Dice { … } class BankAccount { … } class IntegerCalculator { … } class TPMF { … } class bankaccount { … } class numcalc { … }
  • 7. Class Members 7  Class is made up of state and behavior  Fields store state  Methods describe behaviour class Car { String make; String model; void start(){ … } } Fields Method class Dog { int age; String type; void bark(){ … } } Fields Method
  • 8. Creating an Object 8  A class can have many instances (objects) class Program { public static void main() { Car firstCar = new Car(); Car secondCar = new Car(); } } Variable stores a reference Use the new keyword
  • 9.  Declaring a variable creates a reference in the stack  The new keyword allocates memory on the heap Object Reference 9 Car car = new Car(); HEAPSTACK diceD6 (1540e19d) obj type = null sides = 0
  • 10. Classes vs. Objects 10  Classes provide structure for describing and creating objects  An object is a single instance of a class Dice (Class) D6 Dice (Object)
  • 11. Class Data Storing Data Inside a Class
  • 12. Fields 12 public class Car { private String make; private int year; public Person owner; … } Fields can be of any type  Class fields have access modifiers, type and name type access modifier name
  • 13.  Create a class Car  Ensure proper naming! Problem: Define Car Class 13 Car +make:String +model:String +horsePower:int (no actions) Class name Class fields Class methods
  • 14. Solution: Define Car Class 14 public class Car { String make; String model; int horsePower; }
  • 15.  Classes and class members have modifiers  Modifiers define visibility Access Modifiers 15 public class Car { private String make; private String model; } Class modifier Member modifier Fields should always be private!
  • 17.  Store executable code (algorithm) that manipulate state Methods 17 class Car { private int horsePower; public void increaseHP(int value) { horsePower += value; } }
  • 18.  Used to create accessors and mutators (getters and setters) Getters and Setters 18 class Car { private int horsePower; public int getHorsePower() { return this.horsePower; } public void setHorsePower(int horsePower) { this.horsePower = horsePower; } } Field is hidden Getter provides access to field Setter provide field change this points to the current instance
  • 19.  Keyword this  Prevent field hiding  Refers to a current object Getters and Setters 19 private int horsePower; public void setSides(int horsePower) { this.horsePower = horsePower; } public void setSidesNotWorking(int horsePower) { horsePower = horsePower; }
  • 20.  Create a class Car Problem: Car Info 20 Car -make:String … +setMake():void +getMake():String … +carInfo():String + == public - == private return type Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 21. Solution: Car Info 21 public class Car { private String make; private String model; private int horsePower; public void setMake(String make) { this.make = make; } public String getMake() { return this.make; } public String carInfo() { return String.format("The car is: %s %s - %d HP.", this.make, this.model, this.horsePower); } //TODO: Create the other Getters and Setters } //TODO: Test the program Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 23.  Special methods, executed during object creation  The only one way to call a constructor in Java is through the keyword new Constructors 23 public class Car { private String make; public Car() { this.make = "BMW"; } } Overloading default constructor
  • 24.  Special methods, executed during object creation Constructors (1) 24 class Car { private String make; … public Car() { this.make = "unknown"; … } } Overloading default constructor
  • 25.  You can have multiple constructors in the same class Constructors (2) 25 public class Car { private int horsePower; private String make; public Car(String make) { this.make = make; } public Car(String make, int horsePower) { this.make = make; this.horsePower = horsePower; } } Constructor with all parameters Constructor with one parameter
  • 26.  Constructors set object's initial state Object Initial State 26 public class Car { String make; List<Part> parts; public Car(String make) { this.make = make; this.parts = new ArrayList<>(); } } Always ensure correct state
  • 27.  Constructors can call each other Constructor Chaining 27 class Car { private String make; private int horsePower; public Car(String make, int horsePower) { this(make); this.horsePower = horsePower; } public Car(String make) { this.make = make; } }
  • 28.  Create a class Car Problem: Constructors 28 Car -make:String -model:String -horsePower:int +Car(String make) +Car(String make, String model, int horsePower) +carInfo():String Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 29. Solution: Constructors 29 public Car(String make) { this.make = make; this.model = "unknown"; this.horsePower = -1; } public Car(String make, String model, int horsePower) { this(make); this.model = model; this.horsePower = horsePower; } Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 31.  Access static members through the class name  Static members are shared class-wide  You don't need an instance Static Members 31 class Program { public static void main(String[] args) { BankAccount.setInterestRate(2.2); } } Sets the rate for all bank accounts
  • 32. Static Members 32 class BankAccount { private static int accountsCount; private static double interestRate; public BankAccount() { accountsCount++; } public static void setInterestRate(double rate) { interestRate = rate; } }
  • 33.  Create a class BankAccount  Support commands:  Create  Deposit {ID} {Amount}  SetInterest {Interest}  GetInterest {ID} {Years}  End Problem: Bank Account 33 BankAccount -id:int (starts from 1) -balance:double -interestRate:double (default: 0.02) +setInterest(double interest):void +getId():int +getInterest(int years):double +deposit(double amount):void Create Deposit 1 20 GetInterest 1 10 End Account ID1 Created Deposited 20 to ID1 4.00 (20 * 0.02) * 10 underline == static
  • 34. Solution: Bank Account 34 public class BankAccount { private final static double DEFAULT_INTEREST = 0.02; private static double rate = DEFAULT_INTEREST; private static int bankAccountsCount; private int id; private double balance; // continue… Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 35. Solution: Bank Account (2) 35 public BankAccount() { this.id = ++bankAccountsCount; } public static void setInterest(double interest) { rate = interest; } // TODO: int getId() // TODO: double getInterest(int years) // TODO: void deposit(double amount) // TODO: override toString() } Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 36. Solution: Bank Account (2) 36 HashMap<Integer, BankAccount> bankAccounts = new HashMap<>(); while (!command.equals("End")) { //TODO: Get command args switch (cmdType) { case "Create": // TODO case "Deposit": // TODO case "SetInterest": // TODO case "GetInterest": // TODO } //TODO: Read command } Check your solution here: https://judge.softuni.bg/Contests/1517/Defining-Classes-Lab
  • 37.  …  …  … Summary 37  Classes define specific structure for objects  Objects are particular instances of a class  Classes define fields, methods, constructors and other members  Constructors are invoked when creating new class instances  Constructors initialize the object's initial state
  • 41.  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)
  • 42.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 42