Lecture 7 Liang
Lecture 7 Liang
1
Instructor
Mahamudul Hasan
M.Sc.(University of Dhaka), B.Sc.(University of Dhaka).
Senior Lecturer, Department of Computer Science & Engineering
Faculty of Science & Engineering
East West University| Dhaka-1212 | Bangladesh
Tel: +880-2-09666775577 Ext. 256
Mob:+88-01734325208
Email: [email protected]
Web: http://www.ewubd.edu/~mahamudul/
2
OO Programming in Java
Other than primitive data types (byte, short, int, long, float, double, char,
boolean), everything else in Java is of type object.
3
OOP in Java
The programming paradigm where everything is
represented as an object is known as a truly object-
oriented programming language.
Simula is considered the first object-oriented
programming language.
Smalltalk is considered the first truly object-
oriented programming language.
The popular object-oriented languages are Java, C#,
PHP, Python, C++, etc.
4
OOPS
5
Advantage of OOPs over Procedure-
oriented programming language
1) OOPs makes development and maintenance easier whereas in a
procedure-oriented programming language it is not easy to manage if
code grows as project size increases.
2) OOPs provides data hiding whereas in a procedure-oriented
programming language a global data can be accessed from anywhere.
6
What is an Object?
An object represents an entity in the real world that can be distinctly
identified. For example, student, desk, circle, button, person, course,
etc…
7
Object Representation
An object has a unique identity, state, and behaviors.
The memory space is allocated when using the new operator to create
the object.
The memory space holds the values of the data fields (instance
8
variables) of the object.
What is a Class?
A class is the blueprint (template) that defines objects of the
same type, a set of similar object, such as students.
The class uses methods to define the behaviors of its objects.
The class that contains the main method of a Java program
represents the entire program
A class provides a special type of methods, known as
constructors, which are invoked to construct (create) objects
from the class.
Multiple objects can be created from the same class.
Example
A class An object
(the concept) (the realization)
Multiple objects
from the same class
Writing Classes
The programs we’ve written in previous examples have used
classes defined in the Java standard class library.
The class that contains the main method is just the starting
point of a program.
Writing Classes
A class can contain data declarations and method declarations.
BankAccount
String ownerName;
double balance; Data declarations
Deposit()
CheckBalance()
Another Example
Class Name: Circle A class template
Data Fields:
radius is _______
Methods:
getArea
13
Constructor Methods
The contractor method creates the object in the memory with the
help of the Operating System.
Constructors are invoked using the new operator when an object is
created. Constructors play the role of initializing objects.
A class can have multiple versions of the constructor method,
allowing the user to create the class object in different ways.
The constructor method must have same name as the class name.
Constructors do not have a return type, not even void.
A constructor with no parameters is called no-arguments
constructor.
14
UML Class Diagram
15
Class Circle Constructors
class Circle {
// The radius of this circle
double radius = 1.0; Data field
Example:
Circle myCircle1, myCircle2; //reference variables
myCircle1 = new Circle(); //calls first constructor
myCircle2 = new Circle(5.0); //calls second constructor
OR
17
Default Constructor
18
Accessing the Object
Referencing the object’s data:
objectRefVar.data
19
animation
Trace Code
Declare myCircle
yourCircle.radius = 100;
20
animation
Trace Code, cont.
radius: 5.0
Create a circle
21
animation
Trace Code, cont.
22
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
Declare yourCircle
23
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
yourCircle no value
: Circle
Create a new radius: 0.0
Circle object
24
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
Assign object
reference to yourCircle : Circle
radius: 1.0
25
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0); reference value
myCircle
Circle yourCircle = new Circle();
radius: 5.0
: Circle
Change radius in radius: 100.0
yourCircle
26
Caution
Recall that we used
Math.methodName(arguments)
(e.g., Math.pow(3, 2.5))
27
Reference Data Fields
The data fields can be of reference types.
If a data field of a reference type does not reference any object, the
data field holds a special literal value null (or null pointer) .
For example, Class Student contains a data field name of the type
String (an array of characters).
28
Default Value for a Data Field
29
Default Values Inside Methods
Rule: Java assigns no default values to local variables inside a
method. A method's local variables must be initialized.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error: variables not initialized
30
Primitive Type vs. Object Type
radius = 1
31
Primitive Type vs. Object Type
Primitive type assignment i = j
Before: After:
i 1 i 2
j 2 j 2
c1 c1
c2 c2
32
Garbage Collection
On the previous slide, after the assignment statement
c1 = c2; //circle objects
33
Static Variables, Constants, and Methods
34
Java static variable
If you declare any variable as static, it is known as
a static variable.
The static variable can be used to refer to the
common property of all objects (which is not
unique for each object), for example, the company
name of employees, college name of students, etc.
The static variable gets memory only once in the
class area at the time of class loading.
35
Java static variable
class Counter{
int count=0;//will get memory each time when the instance is created
Counter(){
count++;//incrementing value
System.out.println(count);
}
public static void main(String args[]){
//Creating objects
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
36
Java static method
37
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
• //method to display values
38
• void display(){System.out.println(rollno+" "+name+" "+college)
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
• }
•}
39
1.The static method can not use non static data member or call
non-static method directly.
2.this and super cannot be used in static context.
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
40
Static Variables, Constants, and Methods
instantiate Memory
circle1
radius After two Circle
Circle radius = 1 1
objects were created,
numberOfObjects = 2 numberOfObjects
radius: double is 2.
numberOfObjects: int 2 numberOfObjects
41
Visibility Modifiers
By default, a class variable or method can be
accessed by any class in the same package, but not
other packages.
Public:
The class, data, or method is visible to any class in any package.
Private:
The data or method can be accessed only by the declaring class.
The get and set methods are used to read and modify private
variables (better security).
42
Visibility Modifiers Example - 1
44
Data Field Encapsulation
Encapsulation is the idea of hiding the class internal details that are not
required by clients/users of the class.
Why? To protect data and to make classes easy to maintain and update.
How? Always use private variables!
Circle
The - sign indicates
private modifier - radius: double The radius of this circle (default: 1.0).
- numberOfObjects: int The number of circle objects created (static).
45
Java Package
1. A java package is a group of similar types of classes,
interfaces and sub-packages.
2. Package in java can be categorized in two form, built-
in package and user-defined package.
3. There are many built-in packages such as java, lang,
awt, javax, swing, net, io, util, sql etc.
4. Here, we will have the detailed learning of creating and
using user-defined packages.
46
Advantage of Java Package
47
Simple example of java package
The package keyword is used to create a package in java.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
48
49
Example of package that import the packagename.*
50
Access Modifiers in java
51
Visibility Modifiers - Comments - 1
Class members (variables or methods) that are declared with public
visibility can be referenced/accessed anywhere in the program.
52
Visibility Modifiers - Comments - 2
Methods that provide the object's services must be declared with
public visibility so that they can be invoked by clients (users of
the object).
Public methods are also called service methods.
A method created simply to assist a service method is called a
support method.
Since a support method is not intended to be called by a client, it
should be declared with private visibility.
53
Example - 1
public class CircleWithPrivateDataFields
{
private double radius = 1;
private static int numberOfObjects = 0;
54
public class TestCircleWithPrivateDataFields {
Output:
56
public class TestPassObject {
58
Array of Objects
59
Example
public class TotalArea {
public static void main(String[] args) {
// next slide
60
//Print an array of circles and their total area
public static void printCircleArray(
CircleWithPrivateDataFields[] circleArray)
{
System.out.println("Radius" + "\t\t\t\t" + "Area");
for (int i = 0; i < circleArray.length; i++) {
System.out.println(circleArray[i].getRadius() + "\t\t" +
circleArray[i].getArea());
}
System.out.println("-----------------------------------------");
//Compute and display the result
System.out.println("The total areas of circles is\t" +
sum(circleArray));
}
Radius Area
0.049319 0.007642
81.879485 21062.022854
95.330603 28550.554995
92.768319 27036.423936
46.794917 6879.347364
-----------------------------------------
The total areas of circles is 83528.356790
62
Immutable Objects and Classes
If the contents of an object cannot be changed once it is created, the
object is called an immutable object and its class is called an
immutable class.
For example, If you delete the set method in the Circle class in
Listing 8.10, the class would be immutable (not changeable)
because radius is private and cannot be changed without a set
method.
A class with all private data fields and without mutators (set
methods) is not necessarily immutable. For example, the following
class Student has all private data fields and no mutators, but it is
mutable (changeable).
63
Immutable Object Example
public class Student {
public class BirthDate {
private int id;
private int year;
private BirthDate birthDate;
private int month;
private int day;
public Student(int ssn,
int year, int month, int day) {
public BirthDate(int newYear,
id = ssn;
int newMonth, int newDay) {
birthDate = new BirthDate(year,
year = newYear;
month, day);
month = newMonth;
}
day = newDay;
}
public int getId() { return id; }
public void setYear(int newYear)
public BirthDate getBirthDate() {
return birthDate;
{ year = newYear; }
}
}
}
65
Scope of Variables - Revisited
66
The this Keyword
The this keyword is the name of a reference that refers to
an object itself. One common use of this keyword is
referencing a class’s hidden data fields.
67
Referencing the Hidden Data Fields
public class F { Suppose that f1 and f2 are two objects of F.
private int i = 5; F f1 = new F(); F f2 = new F();
private static double k = 0;
Invoking f1.setI(10) is to execute
void setI(int i) { this.i = 10, where this refers f1
this.i = i;
} Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
F.k = k;
}
}
68
Calling Overloaded Constructors
public class Circle {
private double radius;
Output:
Sat Nov 08 12:31:11 EST 2014
70
Class Random - Revisited
You have used Math.random() method to obtain a random
double value between 0.0 and 1.0 (excluding 1.0).
A more useful random number generator is provided in the
java.util.Random class.
java.util.Random
+Random() Constructs a Random object with the current time as its seed.
+Random(seed: long) Constructs a Random object with a specified seed.
+nextInt(): int Returns a random int value.
+nextInt(n: int): int Returns a random int value between 0 and n (exclusive).
+nextLong(): long Returns a random long value.
+nextDouble(): double Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean Returns a random boolean value.
71
Class Random - Revisited
Be Careful! If two Random objects have the same seed, they
will generate identical sequences of numbers.
Example: create two Random objects with the same seed 3.
Random random1 = new Random(3); //seed value is 3
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3); //seed value is 3
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
72
Class Random - Revisited
To avoid that, simply use the current time as the seed value.
From random1: 957 496 459 198 84 788 33 254 441 101
From random2: 583 672 320 735 261 122 956 489 303 120
73
End of Chapter 9
74