SlideShare a Scribd company logo
1 of 42
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

More Related Content

What's hot

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
 

What's hot (20)

14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Basic c#
Basic c#Basic c#
Basic c#
 
C++ oop
C++ oopC++ oop
C++ oop
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
C# Summer course - Lecture 4
C# Summer course - Lecture 4C# Summer course - Lecture 4
C# Summer course - Lecture 4
 
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
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 

Similar to 14. Java defining classes

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
 
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
 
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
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 

Similar to 14. Java defining classes (20)

Unit4_2.pdf
Unit4_2.pdfUnit4_2.pdf
Unit4_2.pdf
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Ch03
Ch03Ch03
Ch03
 
Ch03
Ch03Ch03
Ch03
 
Csharp4 objects and_types
Csharp4 objects and_typesCsharp4 objects and_types
Csharp4 objects and_types
 
Java doc Pr ITM2
Java doc Pr ITM2Java doc Pr ITM2
Java doc Pr ITM2
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Java căn bản - Chapter4
Java căn bản - Chapter4Java căn bản - Chapter4
Java căn bản - Chapter4
 
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
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 
OOP and C++Classes
OOP and C++ClassesOOP and C++Classes
OOP and C++Classes
 
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
 
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
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
C++ L10-Inheritance
C++ L10-InheritanceC++ L10-Inheritance
C++ L10-Inheritance
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 

More from Intro C# Book

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
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
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
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 

Recently uploaded

Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Chandigarh Call girls 9053900678 Call girls in Chandigarh
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
nirzagarg
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
@Chandigarh #call #Girls 9053900678 @Call #Girls in @Punjab 9053900678
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
nirzagarg
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
imonikaupta
 

Recently uploaded (20)

𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
Wagholi & High Class Call Girls Pune Neha 8005736733 | 100% Gennuine High Cla...
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
 
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
Sarola * Female Escorts Service in Pune | 8005736733 Independent Escorts & Da...
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men  🔝mehsana🔝   Escorts...
➥🔝 7737669865 🔝▻ mehsana Call-girls in Women Seeking Men 🔝mehsana🔝 Escorts...
 
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
📱Dehradun Call Girls Service 📱☎️ +91'905,3900,678 ☎️📱 Call Girls In Dehradun 📱
 
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
All Time Service Available Call Girls Mg Road 👌 ⏭️ 6378878445
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
💚😋 Bilaspur Escort Service Call Girls, 9352852248 ₹5000 To 25K With AC💚😋
 
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRLLucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
Lucknow ❤CALL GIRL 88759*99948 ❤CALL GIRLS IN Lucknow ESCORT SERVICE❤CALL GIRL
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 

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