SlideShare a Scribd company logo
Dasar-Dasar Pemrograman 2:
Pemrograman Berbasis Objek
Tim DDP 2 Fasilkom UI
Correspondence: Fariz Darari (fariz@cs.ui.ac.id)
Feel free to use, reuse, and share this work:
the more we share, the more we have!
Why?
Try this one: Create cubes, without using classes.
2
Why?
Try this one: Create cubes, without using classes.
3
Why?
Try this one: Create cubes, without using classes.
4
Why?
Try this one: Create cubes, without using classes.
5
Why?
Try this one: Create cubes, without using classes.
6
It's cumbersome (= ribet)!
Why?
Try this one: Create cubes, now with classes.
7
Why?
Try this one: Create cubes, now with classes.
8
Much simpler, isn't it?
Why?
Try this one: Create cubes, now with classes.
9
Much simpler, isn't it?
Here, the class Cube encapsulates
(= membungkus) related data such
as color and length as a single unit
10
Object-oriented thinking is natural!
Here, we have that the class is Car,
and the objects are, well, all those car instances!
11
And these cute cats?
They are objects as well, of type Cat!
12
Ahh, Human..
Beautiful, yet complicated objects :)
13
Objects can be abstract,
such as ideas, emotions, and knowledge
Hello, OOP!
An object has:
• states (aka. data fields/properties/attributes)
• behaviors (aka. methods)
14
Hello, OOP!
An object has:
• states (aka. data fields/properties/attributes)
• behaviors (aka. methods)
15
Hello, OOP!
An object has:
• states (aka. data fields/properties/attributes)
• behaviors (aka. methods)
16
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
Hello, OOP!
An object has:
• states (aka. data fields/properties/attributes)
• behaviors (aka. methods)
17
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
Class name
Data fields
Constructors
and methods
Objects of Cube
18
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
Objects of Cube
19
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
cube1: Cube
color = "Blue"
length = 1.0
UML Objects
Objects of Cube
20
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
cube1: Cube
color = "Blue"
length = 1.0
cube2: Cube
color = "Red"
length = 2.0
UML Objects
Objects of Cube
21
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
cube1: Cube
color = "Blue"
length = 1.0
cube2: Cube
color = "Red"
length = 2.0
UML Objects
A class is like a factory or a blueprint to create objects
22
..or cookie cutters
Let's code the Cube class!
23
Let's code the Cube class!
24
public class Cube {
String color;
double length;
public Cube() {
this.color = "White";
this.length = 1.0;
}
public Cube(String color, double length) {
this.color = color;
this.length = length;
} // code continues..
Let's code the Cube class!
25
public class Cube {
String color;
double length;
public Cube() {
this.color = "White";
this.length = 1.0;
}
public Cube(String color, double length) {
this.color = color;
this.length = length;
} // code continues..
These two guys are called:
Data fields
Let's code the Cube class!
26
public class Cube {
String color;
double length;
public Cube() {
this.color = "White";
this.length = 1.0;
}
public Cube(String color, double length) {
this.color = color;
this.length = length;
} // code continues..
And these two guys are:
Constructors
These two guys are called:
Data fields
Let's code the Cube class!
27
public String toString() {
return String.format("Cube with length =
%.2f and color = %s",this.length,this.color);
}
public double getVolume() {
return Math.pow(this.length, 3.0);
}
}
Let's code the Cube class!
28
public String toString() {
return String.format("Cube with length =
%.2f and color = %s",this.length,this.color);
}
public double getVolume() {
return Math.pow(this.length, 3.0);
}
}
These are:
Methods
Quiz time: Let's code the Sphere class!
29
public class Sphere {
String color;
double radius;
public Sphere() {
this.color = "White";
this.radius = 1.0;
}
public Sphere(String color, double radius)
{
this.color = color;
this.radius = radius;
} // code continues..
Quiz time: Let's code the Sphere class!
30
// .. continuation
public String toString() {
return String.format("Sphere with radius = %.2f and
color = %s",this.radius,this.color);
}
public double getVolume() {
return 4.0/3 * Math.PI * Math.pow(this.radius, 3.0);
}
}
Quiz time: Is this illegal?
31
public class A { }
Quiz time: Is this illegal?
32
public class A { }
No, this is not illegal (= not not legal = legal :-).
It's the simplest class definition you can have.
When no constructors are defined,
default constructors are used to
instantiate the objects of the class.
Recall the Cube class, let's instantiate it!
33
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
Objects are created using the
new operator, which calls a
relevant constructor
Recall the Cube class, let's instantiate it!
34
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
code inside Cube.java
Objects are created using the
new operator, which calls a
relevant constructor
Recall the Cube class, let's instantiate it!
35
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
code inside Cube.java
Objects are created using the
new operator, which calls a
relevant constructor
Now, let's access the data fields, and
call the methods.
36
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1.color);
System.out.println(cube1.getVolume());
System.out.println(cube2.length);
System.out.println(cube2.getVolume());
Now, let's access the data fields, and
call the methods.
37
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1.color);
System.out.println(cube1.getVolume());
System.out.println(cube2.length);
System.out.println(cube2.getVolume());
Output:
White
1.0
4.0
64.0
Special method: toString()
38
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1);
System.out.println(cube2);
public String toString() { // inside Cube.java
return String.format("Cube with length = %.2f and color = %s",
this.length,this.color);
}
Special method: toString()
39
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1);
System.out.println(cube2);
public String toString() { // inside Cube.java
return String.format("Cube with length = %.2f and color = %s",
this.length,this.color);
}
Printing objects calls the toString() method!
Special method: toString()
40
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1);
System.out.println(cube2);
public String toString() { // inside Cube.java
return String.format("Cube with length = %.2f and color = %s",
this.length,this.color);
}
Output:
Cube with length = 1.00 and color = White
Cube with length = 4.00 and color = Blue
Printing objects calls the toString() method!
Variables store references of objects
41
Cube cube;
cube = new Cube("Red", 2.0);
Cube cubeCopy = cube;
cubeCopy.color = "Blue";
System.out.println(cube.color);
System.out.println(cubeCopy.color);
Variables store references of objects
42
Cube cube;
cube = new Cube("Red", 2.0);
Cube cubeCopy = cube;
cubeCopy.color = "Blue";
System.out.println(cube.color);
System.out.println(cubeCopy.color);
Output:
Blue
Blue
Variables store references of objects
43
Cube cube1 = new Cube("Red", 2.0);
Cube cube2 = new Cube("Red", 2.0);
cube2.color = "Blue";
System.out.println(cube1.color);
System.out.println(cube2.color);
Output:
Red
Blue
null
44
It's a special value, meaning "no object".
You can print it, but..
don't you ever try accessing an attribute or invoke a method of null!
String str = null;
System.out.println(str.length());
null
45
It's a special value, meaning "no object".
You can print it, but..
don't you ever try accessing an attribute or invoke a method of null!
String str = null;
System.out.println(str.length());
Exception in thread "main" java.lang.NullPointerException
Real-world classes: Set
46
import java.util.HashSet;
HashSet<Integer> s1 = new HashSet<Integer>();
HashSet<Integer> s2 = new HashSet<Integer>();
s1.add(3); s1.add(3); s1.add(1); s1.add(2);
s2.add(2); s2.add(0); s2.add(7); s2.add(3);
s1.retainAll(s2);
System.out.println(s1);
Real-world classes: Set
47
import java.util.HashSet;
HashSet<Integer> s1 = new HashSet<Integer>();
HashSet<Integer> s2 = new HashSet<Integer>();
s1.add(3); s1.add(3); s1.add(1); s1.add(2);
s2.add(2); s2.add(0); s2.add(7); s2.add(3);
s1.retainAll(s2);
System.out.println(s1); Output:
[2, 3]
Real-world classes: String
48
String csui = "Fasilkom UI";
System.out.println(csui.charAt(7));
System.out.println(csui.endsWith("UI"));
System.out.println(csui.indexOf("kom"));
System.out.println(csui.replaceAll("UI", "UB"));
System.out.println(csui.toUpperCase());
Real-world classes: String
49
String csui = "Fasilkom UI";
System.out.println(csui.charAt(7));
System.out.println(csui.endsWith("UI"));
System.out.println(csui.indexOf("kom"));
System.out.println(csui.replaceAll("UI", "UB"));
System.out.println(csui.toUpperCase());
Output:
m
true
5
Fasilkom UB
FASILKOM UI
Real-world classes: LocalDate
50
import java.time.LocalDate; // introduced in java 8
LocalDate dateNow = LocalDate.now();
System.out.println(dateNow);
System.out.println(dateNow.getDayOfWeek());
System.out.println(dateNow.plusDays(1));
Real-world classes: LocalDate
51
import java.time.LocalDate; // introduced in java 8
LocalDate dateNow = LocalDate.now();
System.out.println(dateNow);
System.out.println(dateNow.getDayOfWeek());
System.out.println(dateNow.plusDays(1)); // besok
System.out.println(dateNow.plusDays(2)); // lusa
System.out.println(dateNow.plusDays(3)); // tulat
System.out.println(dateNow.plusDays(4)); // tubin
Real-world classes: Random
52
import java.util.Random;
public class GuessStarter {
public static void main(String[] args) {
// pick a random number from 1 to 100
Random random = new Random();
int number = random.nextInt(100) + 1;
System.out.println(number);
}
}
Quiz time: Create a method to initialize an ArrayList of
Integers with n random Integers from 11 to 20!
53
54
public static void initRandom(ArrayList<Integer> lstInt, int n) {
Random rnd = new Random();
while(n > 0) {
lstInt.add(rnd.nextInt(10)+11);
n--;
}
}
Quiz time: Create a method to initialize an ArrayList of
Integers with n random Integers from 11 to 20!
Static variables, constants, and methods
Static means shared by all objects of the class.
55
Cube
color: String
length: double
numOfCubes: int
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
getNumOfCubes(): int
UML Class Diagram
static variable
Static variables, constants, and methods
Static means shared by all objects of the class.
56
Cube
color: String
length: double
numOfCubes: int
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
getNumOfCubes(): int
UML Class Diagram
static variable
static method
Cube.java with static var and method
57
static int numOfCubes = 0; // add this variable
public Cube() {
this.color = "White";
this.length = 1.0;
numOfCubes++; // add this line
}
public Cube(String color, double length) {
this.color = color;
this.length = length;
numOfCubes++; // add this line
}
public static int getNumOfCubes() { // add this method
return numOfCubes;
}
Edit the previous Cube.java accordingly
Cube.java with static var and method
58
static int numOfCubes = 0; // add this variable
public Cube() {
this.color = "White";
this.length = 1.0;
numOfCubes++; // add this line
}
public Cube(String color, double length) {
this.color = color;
this.length = length;
numOfCubes++; // add this line
}
public static int getNumOfCubes() { // add this method
return numOfCubes;
}
Edit the previous Cube.java accordingly
All variables appearing in a static method, must be static!
Cube.java with static var and method
59
System.out.println(Cube.getNumOfCubes());
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1.numOfCubes);
System.out.println(cube2.numOfCubes);
System.out.println(Cube.numOfCubes);
System.out.println(Cube.getNumOfCubes());
Output:
Cube.java with static var and method
60
System.out.println(Cube.getNumOfCubes());
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1.numOfCubes);
System.out.println(cube2.numOfCubes);
System.out.println(Cube.numOfCubes);
System.out.println(Cube.getNumOfCubes());
Output:
0
2
2
2
2
Cube.java with static constant
61
static final String CUBE_MATERIAL = "Silver";
Edit the previous Cube.java accordingly
Cube cube1 = new Cube();
Cube cube2 = new Cube("Blue", 4.0);
System.out.println(cube1.CUBE_MATERIAL);
System.out.println(cube2.CUBE_MATERIAL);
System.out.println(Cube.CUBE_MATERIAL);
Output:
Silver
Silver
Silver
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
62
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
63
public class Time {
int hour;
int minute;
double second;
}
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
64
public class Time {
int hour;
int minute;
double second;
}
We declare the data fields
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
65
public class Time {
int hour;
int minute;
double second;
public Time() {
this.hour = 0;
this.minute = 0;
this.second = 0.0;
}
}
We create a constructor method
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
66
public class Time {
int hour;
int minute;
double second;
public Time() {
this.hour = 0;
this.minute = 0;
this.second = 0.0;
}
}
this behaves like self in Python, it refers to
the object we are creating
We create a constructor method
Quiz time: Create a class of Time, storing
hours, minutes, and integers.
67
// ...
public Time(int hour, int minute, double second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
}
We create another constructor:
this time you can provide
your own values for hour,
minute, and second
Quiz time: Given Time.java, what's the output?
68
Time t1 = new Time();
Time t2 = new Time(11, 30, 10.0);
System.out.println(t1.hour + ":" + t1.minute + ":" + t1.second);
System.out.println(t2.hour + ":" + t2.minute + ":" + t2.second);
Quiz time: Given Time.java, what's the output?
69
Time t1 = new Time();
Time t2 = new Time(11, 30, 10.0);
System.out.println(t1.hour + ":" + t1.minute + ":" + t1.second);
System.out.println(t2.hour + ":" + t2.minute + ":" + t2.second);
Output:
0:0:0.0
11:30:10.0
Quiz time: Now, make a toString method for
Time.java!
70
Quiz time: Now, make a toString method for
Time.java!
71
// inside Time.java
public String toString() {
return String.format("%02d:%02d:%04.1f",
this.hour, this.minute, this.second);
}
}
Quiz time: Now, make a toString method for
Time.java!
72
// inside Time.java
public String toString() {
return String.format("%02d:%02d:%04.1f",
this.hour, this.minute, this.second);
}
} Every object type has a method called toString that returns a string
representation of the object. When you display an object using print or
println, Java invokes the object's toString method.
Quiz time: Given Time.java, what's the output?
73
Time t1 = new Time();
Time t2 = new Time(11, 30, 10.0);
System.out.println(t1);
System.out.println(t2);
Quiz time: Given Time.java, what's the output?
74
Time t1 = new Time();
Time t2 = new Time(11, 30, 10.0);
System.out.println(t1);
System.out.println(t2);
Output:
00:00:00.0
11:30:10.0
Quiz time: Given Time.java, what's the output?
75
Time t3 = new Time(1, 3, 2.1098);
System.out.println(t3);
Quiz time: Given Time.java, what's the output?
76
Output:
01:03:02.1
Time t3 = new Time(1, 3, 2.1098);
System.out.println(t3);
equals method
77
We have seen two ways to check whether values are equal:
the == operator and the equals method. With objects you can use
either one, but they are not the same.
• The == operator checks whether objects are identical; that is,
whether they are the same object (= same memory location).
• The equals method checks whether they are equivalent; that is,
whether they have the same value.
78
What does it mean by "same" in the same value?
equals method
We have seen two ways to check whether values are equal:
the == operator and the equals method. With objects you can use
either one, but they are not the same.
• The == operator checks whether objects are identical; that is,
whether they are the same object (= same memory location).
• The equals method checks whether they are equivalent; that is,
whether they have the same value.
79
What does it mean by "same" in the same value?
We define the equals method for our objects.
equals method
We have seen two ways to check whether values are equal:
the == operator and the equals method. With objects you can use
either one, but they are not the same.
• The == operator checks whether objects are identical; that is,
whether they are the same object (= same memory location).
• The equals method checks whether they are equivalent; that is,
whether they have the same value.
Now, make the equals method for Time.java!
80
// inside Time.java
public boolean equals(Time that) {
return this.hour == that.hour
&& this.minute == that.minute
&& this.second == that.second;
}
}
Now, make the equals method for Time.java!
81
// inside Time.java
public boolean equals(Time that) {
return this.hour == that.hour
&& this.minute == that.minute
&& this.second == that.second;
}
} this always refers to the object that calls the equals method,
the naming of that, however, is arbitrary.
You can replace that with x, bla, or whatever.
Quiz time: Given Time.java, what's the output?
82
Time t1 = new Time(11, 30, 10.0);
Time t2 = new Time(11, 30, 10.0);
Time t3 = new Time(1, 10, 8.1);
System.out.println(t1 == t2);
System.out.println(t1.equals(t2));
System.out.println(t1 == t3);
System.out.println(t1.equals(t3));
Quiz time: Given Time.java, what's the output?
83
Time t1 = new Time(11, 30, 10.0);
Time t2 = new Time(11, 30, 10.0);
Time t3 = new Time(1, 10, 8.1);
System.out.println(t1 == t2);
System.out.println(t1.equals(t2));
System.out.println(t1 == t3);
System.out.println(t1.equals(t3));
Output:
false
true
false
false
Another use of this
84
public class Time {
// ...
public Time() {
this(0, 0, 0.0); // this can be used to call another constructor
}
public Time(int hour, int minute, double second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
// ...
Visibility modifiers
85
• Data fields inside a class are too "open".
• Other classes can directly access the values of those data
fields.
• We need information hiding: a way to control what can be
accessed from outside, and what cannot.
public class Time {
int hour;
int minute;
double second;
}
Visibility modifiers
86
• Solution: Add private to the data fields.
public class Time {
private int hour;
private int minute;
private double second;
}
Visibility modifiers
87
• Solution: Add private to the data fields.
public class Time {
private int hour;
private int minute;
private double second;
}
Can you now access those variables outside the Time class?
Try it out.
Visibility modifiers
88
• Solution: Add private to the data fields.
public class Time {
private int hour;
private int minute;
private double second;
}
We can control what to access by providing:
- Getter methods
- Setter methods
Getters and setters
89
• Recall that the data fields (instance variables) of Time are private. We
can access them from within the Time class, but if we try to access
them from another class, the compiler generates an error.
• For example, here's a new class called TimeClient, trying to access the
private data fields:
public class TimeClient {
public static void main(String[] args) {
Time time = new Time(11, 59, 59.9);
System.out.println(time.hour); // compiler error
}
}
Getters and setters
90
// inside Time.java
public int getHour() {
return this.hour;
}
public int getMinute() {
return this.minute;
}
public double getSecond() {
return this.second;
}
}
Getters and setters
91
// inside Time.java
public void setHour(int hour) {
this.hour = hour;
}
public void setMinute(int minute) {
this.minute = minute;
}
public void setSecond(int second) {
this.second = second;
}
}
Quiz time: Given Time.java, what's the output?
92
Time t1 = new Time(11, 30, 10.0);
System.out.println(t1.getSecond());
System.out.println(t1.getHour());
t1.setMinute(50);
System.out.println(t1.getMinute());
Quiz time: Given Time.java, what's the output?
93
Time t1 = new Time(11, 30, 10.0);
System.out.println(t1.getSecond());
System.out.println(t1.getHour());
t1.setMinute(50);
System.out.println(t1.getMinute());
Output:
10.0
11
50
Recall our Cube.java
94
Cube
color: String
length: double
Cube()
Cube(color: String, length: double)
toString(): String
getVolume(): double
UML Class Diagram
This is the original UML,
now suppose we want the data fields to be private,
and all the methods to be public, what would change?
Recall our Cube.java
95
Cube
-color: String
-length: double
+Cube()
+Cube(color: String, length: double)
+toString(): String
+getVolume(): double
UML Class Diagram
- sign indicates private, while
+ sign indicates not private
Quiz time:
96
Can a Java object have a field of another object?
Quiz time:
97
Can a Java object have a field of another object?
Yes, why not. We have seen an example of this
in Cube.java.
Take-away messages
• Defining a class creates a new object type.
• Every object belongs to some object type.
• A class definition is like a template for objects, it specifies:
• what attributes the objects have; and
• what methods can operate on them.
• The new operator creates new instances of a class.
• Think of a class like a blueprint for a house: you can use the
same blueprint to build any number of houses.
98
Btw, open Java books:
Inspired by:
Liang. Introduction to Java Programming. Tenth Edition. Pearson 2015.
Chapter 10 & 11 of Think Java book by Allen Downey and Chris Mayfield.
Ad

Recommended

Thinking Functionally In Ruby
Thinking Functionally In Ruby
Ross Lawley
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
Bilal Ahmed
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
Aiman Hud
 
Second chapter-java
Second chapter-java
Ahmad sohail Kakar
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
Functional Programming from OO perspective (Sayeret Lambda lecture)
Functional Programming from OO perspective (Sayeret Lambda lecture)
Ittay Dror
 
The Ring programming language version 1.5.3 book - Part 83 of 184
The Ring programming language version 1.5.3 book - Part 83 of 184
Mahmoud Samir Fayed
 
Ggplot2 v3
Ggplot2 v3
Josh Doyle
 
Navidgator - Similarity Based Browsing for Image & Video Databases
Navidgator - Similarity Based Browsing for Image & Video Databases
Damian Borth
 
Datastructure tree
Datastructure tree
rantd
 
Chapter ii(oop)
Chapter ii(oop)
Chhom Karath
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
Introduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object Recognition
Artifacia
 
Pyclustering tutorial - BANG
Pyclustering tutorial - BANG
Andrei Novikov
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
Mahmoud Samir Fayed
 
L10 array
L10 array
teach4uin
 
Applications of datastructures
Applications of datastructures
Ratsietsi Mokete
 
Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Applicationof datastructures
Applicationof datastructures
Hitesh Wagle
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
الوسائط المتعددة Multimedia تاج
الوسائط المتعددة Multimedia تاج
maaz hamed
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
9781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Oops Concept Java
Oops Concept Java
Kamlesh Singh
 
Lab 4
Lab 4
vaminorc
 
Chap08
Chap08
Terry Yoast
 
Java Basics - Part2
Java Basics - Part2
Vani Kandhasamy
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6
RhettB
 
Creating classes and applications in java
Creating classes and applications in java
Gujarat Technological University
 

More Related Content

What's hot (15)

Navidgator - Similarity Based Browsing for Image & Video Databases
Navidgator - Similarity Based Browsing for Image & Video Databases
Damian Borth
 
Datastructure tree
Datastructure tree
rantd
 
Chapter ii(oop)
Chapter ii(oop)
Chhom Karath
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
Introduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object Recognition
Artifacia
 
Pyclustering tutorial - BANG
Pyclustering tutorial - BANG
Andrei Novikov
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
Mahmoud Samir Fayed
 
L10 array
L10 array
teach4uin
 
Applications of datastructures
Applications of datastructures
Ratsietsi Mokete
 
Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Applicationof datastructures
Applicationof datastructures
Hitesh Wagle
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
الوسائط المتعددة Multimedia تاج
الوسائط المتعددة Multimedia تاج
maaz hamed
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 
Navidgator - Similarity Based Browsing for Image & Video Databases
Navidgator - Similarity Based Browsing for Image & Video Databases
Damian Borth
 
Datastructure tree
Datastructure tree
rantd
 
Numpy tutorial(final) 20160303
Numpy tutorial(final) 20160303
Namgee Lee
 
Introduction to CNN with Application to Object Recognition
Introduction to CNN with Application to Object Recognition
Artifacia
 
Pyclustering tutorial - BANG
Pyclustering tutorial - BANG
Andrei Novikov
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
Mahmoud Samir Fayed
 
Applications of datastructures
Applications of datastructures
Ratsietsi Mokete
 
Applicationof datastructures
Applicationof datastructures
Hitesh Wagle
 
Introduction to NumPy for Machine Learning Programmers
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
Lawrence Evans
 
الوسائط المتعددة Multimedia تاج
الوسائط المتعددة Multimedia تاج
maaz hamed
 
The Ring programming language version 1.5.4 book - Part 73 of 185
The Ring programming language version 1.5.4 book - Part 73 of 185
Mahmoud Samir Fayed
 

Similar to Foundations of Programming - Java OOP (20)

9781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Oops Concept Java
Oops Concept Java
Kamlesh Singh
 
Lab 4
Lab 4
vaminorc
 
Chap08
Chap08
Terry Yoast
 
Java Basics - Part2
Java Basics - Part2
Vani Kandhasamy
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6
RhettB
 
Creating classes and applications in java
Creating classes and applications in java
Gujarat Technological University
 
Module 3 Class and Object.ppt
Module 3 Class and Object.ppt
RanjithKumar742256
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
OOP V3.1
OOP V3.1
Sunil OS
 
1 - Classes and Objects OOP.pptx
1 - Classes and Objects OOP.pptx
MohsinIlyas14
 
Object and class
Object and class
mohit tripathi
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
Kuntal Bhowmick
 
Class and Object.pptx
Class and Object.pptx
Hailsh
 
JAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Class & Object - Intro
Class & Object - Intro
PRN USM
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Java basics
Java basics
Shivanshu Purwar
 
9781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
Cso gaddis java_chapter6
Cso gaddis java_chapter6
RhettB
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
1 - Classes and Objects OOP.pptx
1 - Classes and Objects OOP.pptx
MohsinIlyas14
 
Class notes(week 3) on class objects and methods
Class notes(week 3) on class objects and methods
Kuntal Bhowmick
 
Class and Object.pptx
Class and Object.pptx
Hailsh
 
JAVA Module 2____________________--.pptx
JAVA Module 2____________________--.pptx
Radhika Venkatesh
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Class & Object - Intro
Class & Object - Intro
PRN USM
 
Classes, Inheritance ,Packages & Interfaces.pptx
Classes, Inheritance ,Packages & Interfaces.pptx
DivyaKS18
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
DeepVala5
 
Ad

More from Fariz Darari (20)

Data X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMID
Fariz Darari
 
[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf
Fariz Darari
 
Free AI Kit - Game Theory
Free AI Kit - Game Theory
Fariz Darari
 
Neural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An Intro
Fariz Darari
 
NLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it has
Fariz Darari
 
Supply and Demand - AI Talents
Supply and Demand - AI Talents
Fariz Darari
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
AI in education done properly
AI in education done properly
Fariz Darari
 
Artificial Neural Networks: Pointers
Artificial Neural Networks: Pointers
Fariz Darari
 
Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019
Fariz Darari
 
Defense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWD
Fariz Darari
 
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Fariz Darari
 
Recursion in Python
Recursion in Python
Fariz Darari
 
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
Fariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittest
Fariz Darari
 
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Fariz Darari
 
Research Writing - 2018.07.18
Research Writing - 2018.07.18
Fariz Darari
 
KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018
Fariz Darari
 
Comparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness Reasoning
Fariz Darari
 
Data X Museum - Hari Museum Internasional 2022 - WMID
Data X Museum - Hari Museum Internasional 2022 - WMID
Fariz Darari
 
[PUBLIC] quiz-01-midterm-solutions.pdf
[PUBLIC] quiz-01-midterm-solutions.pdf
Fariz Darari
 
Free AI Kit - Game Theory
Free AI Kit - Game Theory
Fariz Darari
 
Neural Networks and Deep Learning: An Intro
Neural Networks and Deep Learning: An Intro
Fariz Darari
 
NLP guest lecture: How to get text to confess what knowledge it has
NLP guest lecture: How to get text to confess what knowledge it has
Fariz Darari
 
Supply and Demand - AI Talents
Supply and Demand - AI Talents
Fariz Darari
 
Basic Python Programming: Part 01 and Part 02
Basic Python Programming: Part 01 and Part 02
Fariz Darari
 
AI in education done properly
AI in education done properly
Fariz Darari
 
Artificial Neural Networks: Pointers
Artificial Neural Networks: Pointers
Fariz Darari
 
Open Tridharma at ICACSIS 2019
Open Tridharma at ICACSIS 2019
Fariz Darari
 
Defense Slides of Avicenna Wisesa - PROWD
Defense Slides of Avicenna Wisesa - PROWD
Fariz Darari
 
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Seminar Laporan Aktualisasi - Tridharma Terbuka - Fariz Darari
Fariz Darari
 
Recursion in Python
Recursion in Python
Fariz Darari
 
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
[ISWC 2013] Completeness statements about RDF data sources and their use for ...
Fariz Darari
 
Testing in Python: doctest and unittest (Updated)
Testing in Python: doctest and unittest (Updated)
Fariz Darari
 
Testing in Python: doctest and unittest
Testing in Python: doctest and unittest
Fariz Darari
 
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Dissertation Defense - Managing and Consuming Completeness Information for RD...
Fariz Darari
 
Research Writing - 2018.07.18
Research Writing - 2018.07.18
Fariz Darari
 
KOI - Knowledge Of Incidents - SemEval 2018
KOI - Knowledge Of Incidents - SemEval 2018
Fariz Darari
 
Comparing Index Structures for Completeness Reasoning
Comparing Index Structures for Completeness Reasoning
Fariz Darari
 
Ad

Recently uploaded (20)

Rierino Commerce Platform - CMS Solution
Rierino Commerce Platform - CMS Solution
Rierino
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
SAP Datasphere Catalog L2 (2024-02-07).pptx
SAP Datasphere Catalog L2 (2024-02-07).pptx
HimanshuSachdeva46
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Insurance Underwriting Software Enhancing Accuracy and Efficiency
Insurance Underwriting Software Enhancing Accuracy and Efficiency
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
Rierino Commerce Platform - CMS Solution
Rierino Commerce Platform - CMS Solution
Rierino
 
Code and No-Code Journeys: The Coverage Overlook
Code and No-Code Journeys: The Coverage Overlook
Applitools
 
OpenTelemetry 101 Cloud Native Barcelona
OpenTelemetry 101 Cloud Native Barcelona
Imma Valls Bernaus
 
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Async-ronizing Success at Wix - Patterns for Seamless Microservices - Devoxx ...
Natan Silnitsky
 
SAP Datasphere Catalog L2 (2024-02-07).pptx
SAP Datasphere Catalog L2 (2024-02-07).pptx
HimanshuSachdeva46
 
Download Adobe Illustrator Crack free for Windows 2025?
Download Adobe Illustrator Crack free for Windows 2025?
grete1122g
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
Application Modernization with Choreo - The AI-Native Internal Developer Plat...
WSO2
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Insurance Underwriting Software Enhancing Accuracy and Efficiency
Insurance Underwriting Software Enhancing Accuracy and Efficiency
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 

Foundations of Programming - Java OOP

  • 1. Dasar-Dasar Pemrograman 2: Pemrograman Berbasis Objek Tim DDP 2 Fasilkom UI Correspondence: Fariz Darari ([email protected]) Feel free to use, reuse, and share this work: the more we share, the more we have!
  • 2. Why? Try this one: Create cubes, without using classes. 2
  • 3. Why? Try this one: Create cubes, without using classes. 3
  • 4. Why? Try this one: Create cubes, without using classes. 4
  • 5. Why? Try this one: Create cubes, without using classes. 5
  • 6. Why? Try this one: Create cubes, without using classes. 6 It's cumbersome (= ribet)!
  • 7. Why? Try this one: Create cubes, now with classes. 7
  • 8. Why? Try this one: Create cubes, now with classes. 8 Much simpler, isn't it?
  • 9. Why? Try this one: Create cubes, now with classes. 9 Much simpler, isn't it? Here, the class Cube encapsulates (= membungkus) related data such as color and length as a single unit
  • 10. 10 Object-oriented thinking is natural! Here, we have that the class is Car, and the objects are, well, all those car instances!
  • 11. 11 And these cute cats? They are objects as well, of type Cat!
  • 12. 12 Ahh, Human.. Beautiful, yet complicated objects :)
  • 13. 13 Objects can be abstract, such as ideas, emotions, and knowledge
  • 14. Hello, OOP! An object has: • states (aka. data fields/properties/attributes) • behaviors (aka. methods) 14
  • 15. Hello, OOP! An object has: • states (aka. data fields/properties/attributes) • behaviors (aka. methods) 15
  • 16. Hello, OOP! An object has: • states (aka. data fields/properties/attributes) • behaviors (aka. methods) 16 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram
  • 17. Hello, OOP! An object has: • states (aka. data fields/properties/attributes) • behaviors (aka. methods) 17 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram Class name Data fields Constructors and methods
  • 18. Objects of Cube 18 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram
  • 19. Objects of Cube 19 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram cube1: Cube color = "Blue" length = 1.0 UML Objects
  • 20. Objects of Cube 20 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram cube1: Cube color = "Blue" length = 1.0 cube2: Cube color = "Red" length = 2.0 UML Objects
  • 21. Objects of Cube 21 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram cube1: Cube color = "Blue" length = 1.0 cube2: Cube color = "Red" length = 2.0 UML Objects A class is like a factory or a blueprint to create objects
  • 23. Let's code the Cube class! 23
  • 24. Let's code the Cube class! 24 public class Cube { String color; double length; public Cube() { this.color = "White"; this.length = 1.0; } public Cube(String color, double length) { this.color = color; this.length = length; } // code continues..
  • 25. Let's code the Cube class! 25 public class Cube { String color; double length; public Cube() { this.color = "White"; this.length = 1.0; } public Cube(String color, double length) { this.color = color; this.length = length; } // code continues.. These two guys are called: Data fields
  • 26. Let's code the Cube class! 26 public class Cube { String color; double length; public Cube() { this.color = "White"; this.length = 1.0; } public Cube(String color, double length) { this.color = color; this.length = length; } // code continues.. And these two guys are: Constructors These two guys are called: Data fields
  • 27. Let's code the Cube class! 27 public String toString() { return String.format("Cube with length = %.2f and color = %s",this.length,this.color); } public double getVolume() { return Math.pow(this.length, 3.0); } }
  • 28. Let's code the Cube class! 28 public String toString() { return String.format("Cube with length = %.2f and color = %s",this.length,this.color); } public double getVolume() { return Math.pow(this.length, 3.0); } } These are: Methods
  • 29. Quiz time: Let's code the Sphere class! 29 public class Sphere { String color; double radius; public Sphere() { this.color = "White"; this.radius = 1.0; } public Sphere(String color, double radius) { this.color = color; this.radius = radius; } // code continues..
  • 30. Quiz time: Let's code the Sphere class! 30 // .. continuation public String toString() { return String.format("Sphere with radius = %.2f and color = %s",this.radius,this.color); } public double getVolume() { return 4.0/3 * Math.PI * Math.pow(this.radius, 3.0); } }
  • 31. Quiz time: Is this illegal? 31 public class A { }
  • 32. Quiz time: Is this illegal? 32 public class A { } No, this is not illegal (= not not legal = legal :-). It's the simplest class definition you can have. When no constructors are defined, default constructors are used to instantiate the objects of the class.
  • 33. Recall the Cube class, let's instantiate it! 33 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); Objects are created using the new operator, which calls a relevant constructor
  • 34. Recall the Cube class, let's instantiate it! 34 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); code inside Cube.java Objects are created using the new operator, which calls a relevant constructor
  • 35. Recall the Cube class, let's instantiate it! 35 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); code inside Cube.java Objects are created using the new operator, which calls a relevant constructor
  • 36. Now, let's access the data fields, and call the methods. 36 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1.color); System.out.println(cube1.getVolume()); System.out.println(cube2.length); System.out.println(cube2.getVolume());
  • 37. Now, let's access the data fields, and call the methods. 37 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1.color); System.out.println(cube1.getVolume()); System.out.println(cube2.length); System.out.println(cube2.getVolume()); Output: White 1.0 4.0 64.0
  • 38. Special method: toString() 38 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1); System.out.println(cube2); public String toString() { // inside Cube.java return String.format("Cube with length = %.2f and color = %s", this.length,this.color); }
  • 39. Special method: toString() 39 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1); System.out.println(cube2); public String toString() { // inside Cube.java return String.format("Cube with length = %.2f and color = %s", this.length,this.color); } Printing objects calls the toString() method!
  • 40. Special method: toString() 40 Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1); System.out.println(cube2); public String toString() { // inside Cube.java return String.format("Cube with length = %.2f and color = %s", this.length,this.color); } Output: Cube with length = 1.00 and color = White Cube with length = 4.00 and color = Blue Printing objects calls the toString() method!
  • 41. Variables store references of objects 41 Cube cube; cube = new Cube("Red", 2.0); Cube cubeCopy = cube; cubeCopy.color = "Blue"; System.out.println(cube.color); System.out.println(cubeCopy.color);
  • 42. Variables store references of objects 42 Cube cube; cube = new Cube("Red", 2.0); Cube cubeCopy = cube; cubeCopy.color = "Blue"; System.out.println(cube.color); System.out.println(cubeCopy.color); Output: Blue Blue
  • 43. Variables store references of objects 43 Cube cube1 = new Cube("Red", 2.0); Cube cube2 = new Cube("Red", 2.0); cube2.color = "Blue"; System.out.println(cube1.color); System.out.println(cube2.color); Output: Red Blue
  • 44. null 44 It's a special value, meaning "no object". You can print it, but.. don't you ever try accessing an attribute or invoke a method of null! String str = null; System.out.println(str.length());
  • 45. null 45 It's a special value, meaning "no object". You can print it, but.. don't you ever try accessing an attribute or invoke a method of null! String str = null; System.out.println(str.length()); Exception in thread "main" java.lang.NullPointerException
  • 46. Real-world classes: Set 46 import java.util.HashSet; HashSet<Integer> s1 = new HashSet<Integer>(); HashSet<Integer> s2 = new HashSet<Integer>(); s1.add(3); s1.add(3); s1.add(1); s1.add(2); s2.add(2); s2.add(0); s2.add(7); s2.add(3); s1.retainAll(s2); System.out.println(s1);
  • 47. Real-world classes: Set 47 import java.util.HashSet; HashSet<Integer> s1 = new HashSet<Integer>(); HashSet<Integer> s2 = new HashSet<Integer>(); s1.add(3); s1.add(3); s1.add(1); s1.add(2); s2.add(2); s2.add(0); s2.add(7); s2.add(3); s1.retainAll(s2); System.out.println(s1); Output: [2, 3]
  • 48. Real-world classes: String 48 String csui = "Fasilkom UI"; System.out.println(csui.charAt(7)); System.out.println(csui.endsWith("UI")); System.out.println(csui.indexOf("kom")); System.out.println(csui.replaceAll("UI", "UB")); System.out.println(csui.toUpperCase());
  • 49. Real-world classes: String 49 String csui = "Fasilkom UI"; System.out.println(csui.charAt(7)); System.out.println(csui.endsWith("UI")); System.out.println(csui.indexOf("kom")); System.out.println(csui.replaceAll("UI", "UB")); System.out.println(csui.toUpperCase()); Output: m true 5 Fasilkom UB FASILKOM UI
  • 50. Real-world classes: LocalDate 50 import java.time.LocalDate; // introduced in java 8 LocalDate dateNow = LocalDate.now(); System.out.println(dateNow); System.out.println(dateNow.getDayOfWeek()); System.out.println(dateNow.plusDays(1));
  • 51. Real-world classes: LocalDate 51 import java.time.LocalDate; // introduced in java 8 LocalDate dateNow = LocalDate.now(); System.out.println(dateNow); System.out.println(dateNow.getDayOfWeek()); System.out.println(dateNow.plusDays(1)); // besok System.out.println(dateNow.plusDays(2)); // lusa System.out.println(dateNow.plusDays(3)); // tulat System.out.println(dateNow.plusDays(4)); // tubin
  • 52. Real-world classes: Random 52 import java.util.Random; public class GuessStarter { public static void main(String[] args) { // pick a random number from 1 to 100 Random random = new Random(); int number = random.nextInt(100) + 1; System.out.println(number); } }
  • 53. Quiz time: Create a method to initialize an ArrayList of Integers with n random Integers from 11 to 20! 53
  • 54. 54 public static void initRandom(ArrayList<Integer> lstInt, int n) { Random rnd = new Random(); while(n > 0) { lstInt.add(rnd.nextInt(10)+11); n--; } } Quiz time: Create a method to initialize an ArrayList of Integers with n random Integers from 11 to 20!
  • 55. Static variables, constants, and methods Static means shared by all objects of the class. 55 Cube color: String length: double numOfCubes: int Cube() Cube(color: String, length: double) toString(): String getVolume(): double getNumOfCubes(): int UML Class Diagram static variable
  • 56. Static variables, constants, and methods Static means shared by all objects of the class. 56 Cube color: String length: double numOfCubes: int Cube() Cube(color: String, length: double) toString(): String getVolume(): double getNumOfCubes(): int UML Class Diagram static variable static method
  • 57. Cube.java with static var and method 57 static int numOfCubes = 0; // add this variable public Cube() { this.color = "White"; this.length = 1.0; numOfCubes++; // add this line } public Cube(String color, double length) { this.color = color; this.length = length; numOfCubes++; // add this line } public static int getNumOfCubes() { // add this method return numOfCubes; } Edit the previous Cube.java accordingly
  • 58. Cube.java with static var and method 58 static int numOfCubes = 0; // add this variable public Cube() { this.color = "White"; this.length = 1.0; numOfCubes++; // add this line } public Cube(String color, double length) { this.color = color; this.length = length; numOfCubes++; // add this line } public static int getNumOfCubes() { // add this method return numOfCubes; } Edit the previous Cube.java accordingly All variables appearing in a static method, must be static!
  • 59. Cube.java with static var and method 59 System.out.println(Cube.getNumOfCubes()); Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1.numOfCubes); System.out.println(cube2.numOfCubes); System.out.println(Cube.numOfCubes); System.out.println(Cube.getNumOfCubes()); Output:
  • 60. Cube.java with static var and method 60 System.out.println(Cube.getNumOfCubes()); Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1.numOfCubes); System.out.println(cube2.numOfCubes); System.out.println(Cube.numOfCubes); System.out.println(Cube.getNumOfCubes()); Output: 0 2 2 2 2
  • 61. Cube.java with static constant 61 static final String CUBE_MATERIAL = "Silver"; Edit the previous Cube.java accordingly Cube cube1 = new Cube(); Cube cube2 = new Cube("Blue", 4.0); System.out.println(cube1.CUBE_MATERIAL); System.out.println(cube2.CUBE_MATERIAL); System.out.println(Cube.CUBE_MATERIAL); Output: Silver Silver Silver
  • 62. Quiz time: Create a class of Time, storing hours, minutes, and integers. 62
  • 63. Quiz time: Create a class of Time, storing hours, minutes, and integers. 63 public class Time { int hour; int minute; double second; }
  • 64. Quiz time: Create a class of Time, storing hours, minutes, and integers. 64 public class Time { int hour; int minute; double second; } We declare the data fields
  • 65. Quiz time: Create a class of Time, storing hours, minutes, and integers. 65 public class Time { int hour; int minute; double second; public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; } } We create a constructor method
  • 66. Quiz time: Create a class of Time, storing hours, minutes, and integers. 66 public class Time { int hour; int minute; double second; public Time() { this.hour = 0; this.minute = 0; this.second = 0.0; } } this behaves like self in Python, it refers to the object we are creating We create a constructor method
  • 67. Quiz time: Create a class of Time, storing hours, minutes, and integers. 67 // ... public Time(int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; } } We create another constructor: this time you can provide your own values for hour, minute, and second
  • 68. Quiz time: Given Time.java, what's the output? 68 Time t1 = new Time(); Time t2 = new Time(11, 30, 10.0); System.out.println(t1.hour + ":" + t1.minute + ":" + t1.second); System.out.println(t2.hour + ":" + t2.minute + ":" + t2.second);
  • 69. Quiz time: Given Time.java, what's the output? 69 Time t1 = new Time(); Time t2 = new Time(11, 30, 10.0); System.out.println(t1.hour + ":" + t1.minute + ":" + t1.second); System.out.println(t2.hour + ":" + t2.minute + ":" + t2.second); Output: 0:0:0.0 11:30:10.0
  • 70. Quiz time: Now, make a toString method for Time.java! 70
  • 71. Quiz time: Now, make a toString method for Time.java! 71 // inside Time.java public String toString() { return String.format("%02d:%02d:%04.1f", this.hour, this.minute, this.second); } }
  • 72. Quiz time: Now, make a toString method for Time.java! 72 // inside Time.java public String toString() { return String.format("%02d:%02d:%04.1f", this.hour, this.minute, this.second); } } Every object type has a method called toString that returns a string representation of the object. When you display an object using print or println, Java invokes the object's toString method.
  • 73. Quiz time: Given Time.java, what's the output? 73 Time t1 = new Time(); Time t2 = new Time(11, 30, 10.0); System.out.println(t1); System.out.println(t2);
  • 74. Quiz time: Given Time.java, what's the output? 74 Time t1 = new Time(); Time t2 = new Time(11, 30, 10.0); System.out.println(t1); System.out.println(t2); Output: 00:00:00.0 11:30:10.0
  • 75. Quiz time: Given Time.java, what's the output? 75 Time t3 = new Time(1, 3, 2.1098); System.out.println(t3);
  • 76. Quiz time: Given Time.java, what's the output? 76 Output: 01:03:02.1 Time t3 = new Time(1, 3, 2.1098); System.out.println(t3);
  • 77. equals method 77 We have seen two ways to check whether values are equal: the == operator and the equals method. With objects you can use either one, but they are not the same. • The == operator checks whether objects are identical; that is, whether they are the same object (= same memory location). • The equals method checks whether they are equivalent; that is, whether they have the same value.
  • 78. 78 What does it mean by "same" in the same value? equals method We have seen two ways to check whether values are equal: the == operator and the equals method. With objects you can use either one, but they are not the same. • The == operator checks whether objects are identical; that is, whether they are the same object (= same memory location). • The equals method checks whether they are equivalent; that is, whether they have the same value.
  • 79. 79 What does it mean by "same" in the same value? We define the equals method for our objects. equals method We have seen two ways to check whether values are equal: the == operator and the equals method. With objects you can use either one, but they are not the same. • The == operator checks whether objects are identical; that is, whether they are the same object (= same memory location). • The equals method checks whether they are equivalent; that is, whether they have the same value.
  • 80. Now, make the equals method for Time.java! 80 // inside Time.java public boolean equals(Time that) { return this.hour == that.hour && this.minute == that.minute && this.second == that.second; } }
  • 81. Now, make the equals method for Time.java! 81 // inside Time.java public boolean equals(Time that) { return this.hour == that.hour && this.minute == that.minute && this.second == that.second; } } this always refers to the object that calls the equals method, the naming of that, however, is arbitrary. You can replace that with x, bla, or whatever.
  • 82. Quiz time: Given Time.java, what's the output? 82 Time t1 = new Time(11, 30, 10.0); Time t2 = new Time(11, 30, 10.0); Time t3 = new Time(1, 10, 8.1); System.out.println(t1 == t2); System.out.println(t1.equals(t2)); System.out.println(t1 == t3); System.out.println(t1.equals(t3));
  • 83. Quiz time: Given Time.java, what's the output? 83 Time t1 = new Time(11, 30, 10.0); Time t2 = new Time(11, 30, 10.0); Time t3 = new Time(1, 10, 8.1); System.out.println(t1 == t2); System.out.println(t1.equals(t2)); System.out.println(t1 == t3); System.out.println(t1.equals(t3)); Output: false true false false
  • 84. Another use of this 84 public class Time { // ... public Time() { this(0, 0, 0.0); // this can be used to call another constructor } public Time(int hour, int minute, double second) { this.hour = hour; this.minute = minute; this.second = second; } // ...
  • 85. Visibility modifiers 85 • Data fields inside a class are too "open". • Other classes can directly access the values of those data fields. • We need information hiding: a way to control what can be accessed from outside, and what cannot. public class Time { int hour; int minute; double second; }
  • 86. Visibility modifiers 86 • Solution: Add private to the data fields. public class Time { private int hour; private int minute; private double second; }
  • 87. Visibility modifiers 87 • Solution: Add private to the data fields. public class Time { private int hour; private int minute; private double second; } Can you now access those variables outside the Time class? Try it out.
  • 88. Visibility modifiers 88 • Solution: Add private to the data fields. public class Time { private int hour; private int minute; private double second; } We can control what to access by providing: - Getter methods - Setter methods
  • 89. Getters and setters 89 • Recall that the data fields (instance variables) of Time are private. We can access them from within the Time class, but if we try to access them from another class, the compiler generates an error. • For example, here's a new class called TimeClient, trying to access the private data fields: public class TimeClient { public static void main(String[] args) { Time time = new Time(11, 59, 59.9); System.out.println(time.hour); // compiler error } }
  • 90. Getters and setters 90 // inside Time.java public int getHour() { return this.hour; } public int getMinute() { return this.minute; } public double getSecond() { return this.second; } }
  • 91. Getters and setters 91 // inside Time.java public void setHour(int hour) { this.hour = hour; } public void setMinute(int minute) { this.minute = minute; } public void setSecond(int second) { this.second = second; } }
  • 92. Quiz time: Given Time.java, what's the output? 92 Time t1 = new Time(11, 30, 10.0); System.out.println(t1.getSecond()); System.out.println(t1.getHour()); t1.setMinute(50); System.out.println(t1.getMinute());
  • 93. Quiz time: Given Time.java, what's the output? 93 Time t1 = new Time(11, 30, 10.0); System.out.println(t1.getSecond()); System.out.println(t1.getHour()); t1.setMinute(50); System.out.println(t1.getMinute()); Output: 10.0 11 50
  • 94. Recall our Cube.java 94 Cube color: String length: double Cube() Cube(color: String, length: double) toString(): String getVolume(): double UML Class Diagram This is the original UML, now suppose we want the data fields to be private, and all the methods to be public, what would change?
  • 95. Recall our Cube.java 95 Cube -color: String -length: double +Cube() +Cube(color: String, length: double) +toString(): String +getVolume(): double UML Class Diagram - sign indicates private, while + sign indicates not private
  • 96. Quiz time: 96 Can a Java object have a field of another object?
  • 97. Quiz time: 97 Can a Java object have a field of another object? Yes, why not. We have seen an example of this in Cube.java.
  • 98. Take-away messages • Defining a class creates a new object type. • Every object belongs to some object type. • A class definition is like a template for objects, it specifies: • what attributes the objects have; and • what methods can operate on them. • The new operator creates new instances of a class. • Think of a class like a blueprint for a house: you can use the same blueprint to build any number of houses. 98
  • 99. Btw, open Java books:
  • 100. Inspired by: Liang. Introduction to Java Programming. Tenth Edition. Pearson 2015. Chapter 10 & 11 of Think Java book by Allen Downey and Chris Mayfield.

Editor's Notes

  • #2: Photo by rawpixel.com from Pexels
  • #8: Assume you have class Cube.
  • #9: One common reason to define a new class is to encapsulate (= bungkus) related data in an object that can be treated as a single unit. That way, we can use objects as parameters and return values, rather than passing and returning multiple values. This design principle is called data encapsulation.
  • #10: One common reason to define a new class is to encapsulate (= bungkus) related data in an object that can be treated as a single unit. That way, we can use objects as parameters and return values, rather than passing and returning multiple values. This design principle is called data encapsulation.
  • #12: https://www.pexels.com/photo/kitten-cat-rush-lucky-cat-45170/
  • #13: https://www.pexels.com/photo/kitten-cat-rush-lucky-cat-45170/
  • #14: https://unsplash.com/photos/gKlnwCvghTU
  • #16: What can be the fields of a cube? What can be the methods of a cube?
  • #17: What can be the fields of a cube? What can be the methods of a cube? cube by shashank singh (https://thenounproject.com)
  • #18: What can be the fields of a cube? What can be the methods of a cube? cube by shashank singh (https://thenounproject.com)
  • #19: cube by shashank singh (https://thenounproject.com)
  • #20: cube by shashank singh (https://thenounproject.com)
  • #21: Question: If there is cube3 with color Blue, and length 1.0, does it mean that cube3 is the same object as cube1? cube by shashank singh (https://thenounproject.com)
  • #22: cube by shashank singh (https://thenounproject.com) The non-static parts of the class specify, or describe, what variables and methods the objects will contain. This is part of the explanation of how objects differ from classes: Objects are created and destroyed as the program runs, and there can be many objects with the same structure, if they are created using the same class. (DJE)
  • #23: Or cookie cutters https://www.pexels.com/photo/brown-wooden-table-669738/
  • #24: Interactive mode!
  • #26: Constructors = methods to construct objects Rules: same name as class name + no return type + called with "new ClassName()"
  • #27: Constructors = methods to construct objects Rules: same name as class name + no return type + called with "new ClassName()"
  • #30: https://www.pexels.com/photo/photo-of-ball-pit-balls-681118/
  • #31: https://www.pexels.com/photo/photo-of-ball-pit-balls-681118/
  • #44: Why? The new operator creates a new object (hence different memory location)
  • #48: retain = keep
  • #63: The data encapsulated in a Time object are an hour, a minute, and a number of seconds. Because every Time object contains these data, we define attributes to hold them.
  • #64: The data encapsulated in a Time object are an hour, a minute, and a number of seconds. Because every Time object contains these data, we define attributes to hold them.
  • #65: They are instance variables, instead of static variables, because there is no static.
  • #67: The name this is a keyword that refers to the object we are creating. You can use this the same way you use the name of any other object. For example, you can read and write the instance variables of this, and you can pass this as an argument to other methods. But you do not declare this, and you can't make an assignment to it.
  • #68: Like other methods, constructors can be overloaded, which means you can provide multiple constructors with di erent parameters. Java knows which constructor to invoke by matching the arguments you provide with the pa- rameters of the constructors.
  • #79: Same memory location is clear. What it means by same value?
  • #80: Same memory location is clear. What it means by same value?
  • #91: Getters are called accessors too
  • #92: Getters are called accessors too, and setters are called mutators too
  • #95: cube by shashank singh (https://thenounproject.com)
  • #96: cube by shashank singh (https://thenounproject.com)
  • #100: https://www.ossblog.org/learn-java-programming-with-excellent-open-source-books/
  • #101: Picture: https://unsplash.com/photos/VyC0YSFRDTU