SlideShare a Scribd company logo
1 of 47
Working with Abstraction
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Architecture, Refactoring and Enumerations
Table of Contents
1. Project Architecture
 Methods
 Classes
 Projects
2. Code Refactoring
3. Enumerations
4. Static Keyword
5. Java Packages
2
sli.do
#java-advanced
Have a Question?
Project Architecture
Splitting Code into Logical Parts
 We use methods to split code into functional blocks
 Improves code readability
 Allows for easier debugging
Splitting Code into Methods (1)
5
for (char move : moves){
for (int r = 0; r < room.length; r++)
for (int c = 0; c < room[r].length; c++)
if (room[row][col] == 'b')
…
}
for (char move : moves) {
moveEnemies();
killerCheck();
movePlayer(move);
}
 Methods let us easily reuse code
 We change the method once to affect all calls
Splitting Code into Methods (2)
6
BankAccount bankAcc = new BankAccount();
bankAcc.setId(1);
bankAcc.deposit(20);
System.out.printf("Account %d, balance %d",
bankAcc.getId(),bankAcc.getBalance());
bankAcc.withdraw(10);
…
System.out.println(bankAcc.ToString());
Override .toString() to
set a global printing format
 A single method should complete a single task
void withdraw ( … )
void deposit ( … )
BigDecimal getBalance ( … )
string toString ( … )
Splitting Code into Methods (3)
7
void doMagic ( … )
void depositOrWithdraw ( … )
BigDecimal depositAndGetBalance ( … )
String parseDataAndReturnResult ( … )
 Draw on the console a rhombus of stars with size n
Problem: Rhombus of Stars
8
*
* *
* * *
* *
*
n = 3
*
* *
*
n = 2
*
n = 1
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Rhombus of Stars (1)
9
int size = Integer.parseInt(sc.nextLine());
for (int starCount = 1; starCount <= size; starCount++) {
printRow(size, starCount);
}
for (int starCount = size - 1; starCount >= 1; starCount--) {
printRow(size, starCount);
}
Reusing code
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Rhombus of Stars (2)
10
static void printRow(int figureSize, int starCount) {
for (int i = 0; i < figureSize - starCount; i++)
System.out.print(" ");
for (int col = 1; col < starCount; col++) {
System.out.print("* ");
}
System.out.println("*");
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Splitting Code into Classes (1)
 Just like methods, classes should not
know or do too much
11
GodMode master = new GodMode();
int[] numbers = master.parseAny(input);
...
int[] numbers2 = master.copyAny(numbers);
master.printToConsole(master.getDate());
master.printToConsole(numbers);
 We can also break our code up logically into classes
 Hiding implementation
 Allow us to change output destination
 Helps us to avoid repeating code
Splitting Code into Classes (2)
12
Splitting Code into Classes (3)
13
List<Integer> input = Arrays.stream(
sc.nextLine().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
...
String result = input.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "));
System.out.println(result);
ArrayParser parser = new ArrayParser();
OuputWriter printer = new OuputWriter();
int[] numbers = parser.integersParse(args);
int[] coordinates = parser.integerParse(args1);
printer.printToConsole(numbers);
 Create a Point class holding the horizontal and vertical coordinates
 Create a Rectangle class
 Holds 2 points
 Bottom left and top right
 Add Contains method
 Takes a Point as an argument
 Returns it if it’s inside the current object of the Rectangle class
Problem: Point in Rectangle
14
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Point in Rectangle
15
public class Point {
private int x;
private int y;
//TODO: Add getters and setters
}
public class Rectangle {
private Point bottomLeft;
private Point topRight;
//TODO: getters and setters
public boolean contains(Point point) {
//TODO: Implement
}
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Point in Rectangle (2)
16
public boolean contains(Point point)
{
boolean isInHorizontal =
this.bottomLeft.getX() <= point.getX() &&
this.topRight.getX() >= point.getX();
boolean isInVertical =
this.bottomLeft.getY() <= point.getY() &&
this.topRight.getY() >= point.getY();
boolean isInRectangle = isInHorizontal &&
isInVertical;
return isInRectangle;
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Refactoring
Restructuring and Organizing Code
 Restructures code without changing the behaviour
 Improves code readability
 Reduces complexity
Refactoring
18
class ProblemSolver { public static void doMagic() { … } }
class CommandParser {
public static <T> Function<T, T> parseCommand() { … } }
class DataModifier { public static <T> T execute() { … } }
class OutputFormatter { public static void print() { … } }
 Breaking code into reusable units
 Extracting parts of methods and classes into new ones
Refactoring Techniques
19
depositOrWithdraw()
 Improving names of variables, methods, classes, etc.
deposit()
withdraw()
 Moving methods or fields to more appropriate classes
String str; String name;
Car.open() Door.open()
 You are given a working Student System project to refactor
 Break it up into smaller functional units and make sure it works
 It supports the following commands:
 "Create <studentName> <studentAge> <studentGrade>"
 creates a new student
 "Show <studentName>"
 prints information about a student
 "Exit"
 closes the program
Problem: Student System
20
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Enumerations
Syntax and Usage
 Represent a numeric value from a fixed set as a text
 We can use them to pass arguments to methods
without making code confusing
 By default enums start at 0
 Every next value is incremented by 1
Enumerations
22
GetDailySchedule(0) GetDailySchedule(Day.Mon)
enum Day {Mon, Tue, Wed, Thu, Fri, Sat, Sun}
 We can customize enum values
Enumerations (1)
23
enum Day {
Mon(1),Tue(2),Wed(3),Thu(4),Fri(5),Sat(6),Sun(7);
private int value;
Day(int value) {
this.value = value;
}
}
System.out.println(Day.Sat); // Sat
 We can customize enum values
Enumerations (2)
24
enum CoffeeSize {
Small(100), Normal(150), Double(300);
private int size;
CoffeeSize(int size) {
this.size = size;
}
public int getValue() { return this.size; }
}
System.out.println(CoffeeSize.Small.getValue()); // 100
 Create a class PriceCalculator that calculates the total price of a holiday,
by given price per day, number of days, the season and a discount type
 The discount type and season
should be enums
 The price multipliers will be:
 1x for Autumn, 2x for Spring, etc.
 The discount types will be:
 None – 0%
 SecondVisit – 10%
 VIP – 20%
Problem: Hotel Reservation
25Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Hotel Reservation (1)
26
public enum Season {
Spring(2), Summer(4), Autumn(1), Winter(3);
private int value;
Season(int value) {
this.value = value;
}
public int getValue(){
return this.value;
}
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Hotel Reservation (2)
27
public enum Discount {
None(0), SecondVisit(10), VIP(20);
private int value;
Discount(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Solution: Hotel Reservation (3)
28
public class PriceCalculator {
public static double CalculatePrice(double pricePerDay,
int numberOfDays, Season season, Discount discount) {
int multiplier = season.getValue();
double discountMultiplier = discount.getValue() / 100.0;
double priceBeforeDiscount = numberOfDays * pricePerDay * multiplier;
double discountedAmount = priceBeforeDiscount * discountMultiplier;
return priceBeforeDiscount - discountedAmount;
}
}
Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
Static Keyword in Java
Static Class, Variable, Method and Block
29
 Used for memory management mainly
 Can apply with:
 Nested class
 Variables
 Methods
 Blocks
 Belongs to the class than an instance of the class
Static Keyword
static int count;
static void increaseCount() {
count++;
}
 A top level class is a class that is not a nested class
 A nested class is any class whose declaration occurs
within the body of another class or interface
 Only nested classes can be static
Static Class
class TopClass {
static class NestedStaticClass {
}
}
 Can be used to refer to the common
variable of all objects
 Еxample
 The company name of employees
 College name of students
 Name of the college is common for all students
 Allocate memory only once in class area
at the time of class loading
Static Variable
Example: Static Variable (1)
33
class Counter {
int count = 0; static int staticCount = 0;
public Counter() {
count++; // incrementing value
staticCount++; // incrementing value
}
public void printCounters() {
System.out.printf("Count: %d%n", count);
System.out.printf("Static Count: %d%n", staticCount);
}
}
Example: Static Variable (2)
34
// Inside the Main Class
public static void main(String[] args) {
Counter c1 = new Counter();
c1.printCounters();
Counter c2 = new Counter();
c2.printCounters();
Counter c3 = new Counter();
c3.printCounters();
int counter = Counter.staticCount; // 3
}
Count: 1
Static Count: 1
Count: 1
Static Count: 2
Count: 1
Static Count: 3
 Belongs to the class rather than the object of a class
 Can be invoked without the need for creating
an instance of a class
 Can access static data member and can change
the value of it
 Can not use non-static data member or call
non-static method directly
 this and super cannot be used in static context
Static Method
35
class Calculate {
static int cube(int x) { return x * x * x; }
public static void main(String args[]) {
int result = Calculate.cube(5);
System.out.println(result); // 125
System.out.println(Math.pow(2, 3)); // 8.0
}
}
Example: Static Method
36
 A set of statements, which will be executed by the
JVM before execution of main method
 Executing static block is at the time of class loading
 A class can take any number of static block but all
blocks will be executed from top to bottom
Static Block
37
class Main {
static int n;
public static void main(String[] args) {
System.out.println("From main");
System.out.println(n);
}
static {
System.out.println("From static block");
n = 10;
}
}
Example: Static Block
38
From static block
From main
10
Packages
Built-In and User-Defined Packages
39
 Used to group related classes
 Like a folder in a file directory
 Use packages to avoid name conflicts and to write a
better maintainable code
 Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create own packages)
Packages in Java
 The library is divided into packages and classes
 Import a single class or a whole package that contain
all the classes
 To use a class or a package, use the import keyword
 The complete list can be found at Oracles website:
https://docs.oracle.com/en/java/javase/
Build-In Packages
41
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
 …
 …
 …
Summary
42
 Well organized code is easier to work with
 We can reduce complexity using
Methods, Classes and Projects
 We can refactor existing code by
breaking code down
 Enumerations define a fixed set of constants
 Represent numeric values
 We can easily cast enums to numeric types
 Static members and Packages
 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-
NonCommercial-ShareAlike 4.0 International" license
License
47

More Related Content

What's hot

16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism 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 ComplexityIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro 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
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and ClassesIntro C# Book
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling 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 indiaSanjeev Tripathi
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro 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 complexityIntro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 

What's hot (20)

16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
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
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
11. Objects and Classes
11. Objects and Classes11. Objects and Classes
11. Objects and Classes
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
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
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
06.Loops
06.Loops06.Loops
06.Loops
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 

Similar to 20.1 Java working with abstraction

Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedPascal-Louis Perez
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings imtiazalijoono
 
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 ConversionSvetlin Nakov
 
Boost delivery stream with code discipline engineering
Boost delivery stream with code discipline engineeringBoost delivery stream with code discipline engineering
Boost delivery stream with code discipline engineeringMiro Wengner
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Palak Sanghani
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)Chhom Karath
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And EnumsBhushan Mulmule
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 

Similar to 20.1 Java working with abstraction (20)

00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Programming Fundamentals Arrays and Strings
Programming Fundamentals   Arrays and Strings Programming Fundamentals   Arrays and Strings
Programming Fundamentals Arrays and Strings
 
Clean code
Clean codeClean code
Clean code
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 
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
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
Boost delivery stream with code discipline engineering
Boost delivery stream with code discipline engineeringBoost delivery stream with code discipline engineering
Boost delivery stream with code discipline engineering
 
Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]Lec 8 03_sept [compatibility mode]
Lec 8 03_sept [compatibility mode]
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Arrays, Structures And Enums
Arrays, Structures And EnumsArrays, Structures And Enums
Arrays, Structures And Enums
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 

More from 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 traversalIntro 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 CodeIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks QueuesIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

More from Intro C# Book (10)

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
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
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
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
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
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Recently uploaded

Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Servicegwenoracqe6
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...sonatiwari757
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
horny (9316020077 ) Goa Call Girls Service by VIP Call Girls in Goa
horny (9316020077 ) Goa  Call Girls Service by VIP Call Girls in Goahorny (9316020077 ) Goa  Call Girls Service by VIP Call Girls in Goa
horny (9316020077 ) Goa Call Girls Service by VIP Call Girls in Goasexy call girls service in goa
 
𓀤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...Neha Pandey
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Servicesexy call girls service in goa
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
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 👌 ⏭️ 6378878445ruhi
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceDelhi Call girls
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
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 GIRLimonikaupta
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 

Recently uploaded (20)

Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
Call Girls in Mayur Vihar ✔️ 9711199171 ✔️ Delhi ✔️ Enjoy Call Girls With Our...
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
horny (9316020077 ) Goa Call Girls Service by VIP Call Girls in Goa
horny (9316020077 ) Goa  Call Girls Service by VIP Call Girls in Goahorny (9316020077 ) Goa  Call Girls Service by VIP Call Girls in Goa
horny (9316020077 ) Goa Call Girls Service by VIP Call Girls in Goa
 
𓀤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...
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine ServiceHot Service (+9316020077 ) Goa  Call Girls Real Photos and Genuine Service
Hot Service (+9316020077 ) Goa Call Girls Real Photos and Genuine Service
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
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
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICECall Girls In Noida 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
Call Girls In Noida 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SERVICE
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
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
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 

20.1 Java working with abstraction

  • 1. Working with Abstraction Software University http://softuni.bg SoftUni Team Technical Trainers Architecture, Refactoring and Enumerations
  • 2. Table of Contents 1. Project Architecture  Methods  Classes  Projects 2. Code Refactoring 3. Enumerations 4. Static Keyword 5. Java Packages 2
  • 5.  We use methods to split code into functional blocks  Improves code readability  Allows for easier debugging Splitting Code into Methods (1) 5 for (char move : moves){ for (int r = 0; r < room.length; r++) for (int c = 0; c < room[r].length; c++) if (room[row][col] == 'b') … } for (char move : moves) { moveEnemies(); killerCheck(); movePlayer(move); }
  • 6.  Methods let us easily reuse code  We change the method once to affect all calls Splitting Code into Methods (2) 6 BankAccount bankAcc = new BankAccount(); bankAcc.setId(1); bankAcc.deposit(20); System.out.printf("Account %d, balance %d", bankAcc.getId(),bankAcc.getBalance()); bankAcc.withdraw(10); … System.out.println(bankAcc.ToString()); Override .toString() to set a global printing format
  • 7.  A single method should complete a single task void withdraw ( … ) void deposit ( … ) BigDecimal getBalance ( … ) string toString ( … ) Splitting Code into Methods (3) 7 void doMagic ( … ) void depositOrWithdraw ( … ) BigDecimal depositAndGetBalance ( … ) String parseDataAndReturnResult ( … )
  • 8.  Draw on the console a rhombus of stars with size n Problem: Rhombus of Stars 8 * * * * * * * * * n = 3 * * * * n = 2 * n = 1 Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 9. Solution: Rhombus of Stars (1) 9 int size = Integer.parseInt(sc.nextLine()); for (int starCount = 1; starCount <= size; starCount++) { printRow(size, starCount); } for (int starCount = size - 1; starCount >= 1; starCount--) { printRow(size, starCount); } Reusing code Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 10. Solution: Rhombus of Stars (2) 10 static void printRow(int figureSize, int starCount) { for (int i = 0; i < figureSize - starCount; i++) System.out.print(" "); for (int col = 1; col < starCount; col++) { System.out.print("* "); } System.out.println("*"); } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 11. Splitting Code into Classes (1)  Just like methods, classes should not know or do too much 11 GodMode master = new GodMode(); int[] numbers = master.parseAny(input); ... int[] numbers2 = master.copyAny(numbers); master.printToConsole(master.getDate()); master.printToConsole(numbers);
  • 12.  We can also break our code up logically into classes  Hiding implementation  Allow us to change output destination  Helps us to avoid repeating code Splitting Code into Classes (2) 12
  • 13. Splitting Code into Classes (3) 13 List<Integer> input = Arrays.stream( sc.nextLine().split(" ")) .map(Integer::parseInt) .collect(Collectors.toList()); ... String result = input.stream() .map(String::valueOf) .collect(Collectors.joining(", ")); System.out.println(result); ArrayParser parser = new ArrayParser(); OuputWriter printer = new OuputWriter(); int[] numbers = parser.integersParse(args); int[] coordinates = parser.integerParse(args1); printer.printToConsole(numbers);
  • 14.  Create a Point class holding the horizontal and vertical coordinates  Create a Rectangle class  Holds 2 points  Bottom left and top right  Add Contains method  Takes a Point as an argument  Returns it if it’s inside the current object of the Rectangle class Problem: Point in Rectangle 14 Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 15. Solution: Point in Rectangle 15 public class Point { private int x; private int y; //TODO: Add getters and setters } public class Rectangle { private Point bottomLeft; private Point topRight; //TODO: getters and setters public boolean contains(Point point) { //TODO: Implement } } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 16. Solution: Point in Rectangle (2) 16 public boolean contains(Point point) { boolean isInHorizontal = this.bottomLeft.getX() <= point.getX() && this.topRight.getX() >= point.getX(); boolean isInVertical = this.bottomLeft.getY() <= point.getY() && this.topRight.getY() >= point.getY(); boolean isInRectangle = isInHorizontal && isInVertical; return isInRectangle; } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 18.  Restructures code without changing the behaviour  Improves code readability  Reduces complexity Refactoring 18 class ProblemSolver { public static void doMagic() { … } } class CommandParser { public static <T> Function<T, T> parseCommand() { … } } class DataModifier { public static <T> T execute() { … } } class OutputFormatter { public static void print() { … } }
  • 19.  Breaking code into reusable units  Extracting parts of methods and classes into new ones Refactoring Techniques 19 depositOrWithdraw()  Improving names of variables, methods, classes, etc. deposit() withdraw()  Moving methods or fields to more appropriate classes String str; String name; Car.open() Door.open()
  • 20.  You are given a working Student System project to refactor  Break it up into smaller functional units and make sure it works  It supports the following commands:  "Create <studentName> <studentAge> <studentGrade>"  creates a new student  "Show <studentName>"  prints information about a student  "Exit"  closes the program Problem: Student System 20 Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 22.  Represent a numeric value from a fixed set as a text  We can use them to pass arguments to methods without making code confusing  By default enums start at 0  Every next value is incremented by 1 Enumerations 22 GetDailySchedule(0) GetDailySchedule(Day.Mon) enum Day {Mon, Tue, Wed, Thu, Fri, Sat, Sun}
  • 23.  We can customize enum values Enumerations (1) 23 enum Day { Mon(1),Tue(2),Wed(3),Thu(4),Fri(5),Sat(6),Sun(7); private int value; Day(int value) { this.value = value; } } System.out.println(Day.Sat); // Sat
  • 24.  We can customize enum values Enumerations (2) 24 enum CoffeeSize { Small(100), Normal(150), Double(300); private int size; CoffeeSize(int size) { this.size = size; } public int getValue() { return this.size; } } System.out.println(CoffeeSize.Small.getValue()); // 100
  • 25.  Create a class PriceCalculator that calculates the total price of a holiday, by given price per day, number of days, the season and a discount type  The discount type and season should be enums  The price multipliers will be:  1x for Autumn, 2x for Spring, etc.  The discount types will be:  None – 0%  SecondVisit – 10%  VIP – 20% Problem: Hotel Reservation 25Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 26. Solution: Hotel Reservation (1) 26 public enum Season { Spring(2), Summer(4), Autumn(1), Winter(3); private int value; Season(int value) { this.value = value; } public int getValue(){ return this.value; } } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 27. Solution: Hotel Reservation (2) 27 public enum Discount { None(0), SecondVisit(10), VIP(20); private int value; Discount(int value) { this.value = value; } public int getValue() { return this.value; } } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 28. Solution: Hotel Reservation (3) 28 public class PriceCalculator { public static double CalculatePrice(double pricePerDay, int numberOfDays, Season season, Discount discount) { int multiplier = season.getValue(); double discountMultiplier = discount.getValue() / 100.0; double priceBeforeDiscount = numberOfDays * pricePerDay * multiplier; double discountedAmount = priceBeforeDiscount * discountMultiplier; return priceBeforeDiscount - discountedAmount; } } Check your solution here :https://judge.softuni.bg/Contests/1575/Working-with-Abstraction-Lab
  • 29. Static Keyword in Java Static Class, Variable, Method and Block 29
  • 30.  Used for memory management mainly  Can apply with:  Nested class  Variables  Methods  Blocks  Belongs to the class than an instance of the class Static Keyword static int count; static void increaseCount() { count++; }
  • 31.  A top level class is a class that is not a nested class  A nested class is any class whose declaration occurs within the body of another class or interface  Only nested classes can be static Static Class class TopClass { static class NestedStaticClass { } }
  • 32.  Can be used to refer to the common variable of all objects  Еxample  The company name of employees  College name of students  Name of the college is common for all students  Allocate memory only once in class area at the time of class loading Static Variable
  • 33. Example: Static Variable (1) 33 class Counter { int count = 0; static int staticCount = 0; public Counter() { count++; // incrementing value staticCount++; // incrementing value } public void printCounters() { System.out.printf("Count: %d%n", count); System.out.printf("Static Count: %d%n", staticCount); } }
  • 34. Example: Static Variable (2) 34 // Inside the Main Class public static void main(String[] args) { Counter c1 = new Counter(); c1.printCounters(); Counter c2 = new Counter(); c2.printCounters(); Counter c3 = new Counter(); c3.printCounters(); int counter = Counter.staticCount; // 3 } Count: 1 Static Count: 1 Count: 1 Static Count: 2 Count: 1 Static Count: 3
  • 35.  Belongs to the class rather than the object of a class  Can be invoked without the need for creating an instance of a class  Can access static data member and can change the value of it  Can not use non-static data member or call non-static method directly  this and super cannot be used in static context Static Method 35
  • 36. class Calculate { static int cube(int x) { return x * x * x; } public static void main(String args[]) { int result = Calculate.cube(5); System.out.println(result); // 125 System.out.println(Math.pow(2, 3)); // 8.0 } } Example: Static Method 36
  • 37.  A set of statements, which will be executed by the JVM before execution of main method  Executing static block is at the time of class loading  A class can take any number of static block but all blocks will be executed from top to bottom Static Block 37
  • 38. class Main { static int n; public static void main(String[] args) { System.out.println("From main"); System.out.println(n); } static { System.out.println("From static block"); n = 10; } } Example: Static Block 38 From static block From main 10
  • 40.  Used to group related classes  Like a folder in a file directory  Use packages to avoid name conflicts and to write a better maintainable code  Packages are divided into two categories:  Built-in Packages (packages from the Java API)  User-defined Packages (create own packages) Packages in Java
  • 41.  The library is divided into packages and classes  Import a single class or a whole package that contain all the classes  To use a class or a package, use the import keyword  The complete list can be found at Oracles website: https://docs.oracle.com/en/java/javase/ Build-In Packages 41 import package.name.Class; // Import a single class import package.name.*; // Import the whole package
  • 42.  …  …  … Summary 42  Well organized code is easier to work with  We can reduce complexity using Methods, Classes and Projects  We can refactor existing code by breaking code down  Enumerations define a fixed set of constants  Represent numeric values  We can easily cast enums to numeric types  Static members and Packages
  • 46.  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)
  • 47.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license License 47

Editor's Notes

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*