09slide Comp2311
09slide Comp2311
OBJECT-ORIENTED PROGRAMMING
COMP2311
Instructor :Murad Njoum
Office : Masri322
1
2
Classes
Classes are constructs that define objects of the same type. A
Java class uses variables to define data fields and methods
to define behaviours. Additionally, a class provides a
particular type of method, known as constructors, invoked to
construct objects from the class.
3
4
5
6
7
8
UML Class Diagram: Unified Modeling Language
UML Class Diagram Circle Class name
9
Constructors
Constructors are a special
Circle() {
} kind of method that are
invoked to construct objects.
Circle(double newRadius) {
radius = newRadius;
}
10
Constructors, cont.
A constructor with no parameters is referred to as a no-arg
constructor.
v Constructors must have the same name as the class itself.
v Constructors do not have a return type—not even void.
v Constructors are invoked using the new operator when an
object is created. Constructors play the role of initializing
objects.
11
Default Constructor
A class may be defined without constructors. In this case, a no-arg
constructor with an empty body is implicitly defined in the class.
This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly defined in
the class.
12
Default Value for a Data Field
The default value of a data field is null for a reference
type, 0 for a numeric type, false for a boolean type, and
'\u0000' for a char type. However, Java assigns no default
value to a local variable inside a method.
public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
13
Example
Java assigns no default value to a local variable inside a
method.
àAny variable inside the method should be initialized.
à But, Inside the class, it has a default value.
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);
}
}
radius = 1
15
Garbage Collection,
16
The Date Class
Java provides a system-independent encapsulation of date and
time in the java.util.Date class. You can use the Date class to
create an instance for the current date and time and use its
toString method to return the date and time as a string.
java.util.Date
The + sign indicates
public modifer +Date() Constructs a Date object for the current time.
+Date(elapseTime: long) Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String Returns a string representing the date and time.
+getTime(): long Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void Sets a new elapse time in the object.
17
The Date Class Example
For example, the following code
18
The Random Class
You have used Math.random() 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.
19
The Random Class Example
If two Random objects have the same seed, they will generate
identical sequences of numbers. For example, the following code
creates two Random objects with the same seed 3.
Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(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
20
variables in Java:
• There are three main variables in Java:
1. Local variable
2 . Instance variables
3 . Class/Static variables.
21
Example:
public class Employee {
public String Name; // Name is an instance variable
with public access modifier
23
Instance
Variables, and Methods
•
Instance methods are invoked by an instance of the class.
24
Static Variables, Constants, and Methods
26
public class CircleWithStaticMembers { /** Construct a circle with a specified radius */
/** The radius of the circle */ CircleWithStaticMembers(double newRadius)
double radius; {
radius = newRadius;
/** The number of the objects created */ numberOfObjects++;
static int numberOfObjects = 0; }
29
Difference between instance and static
variables:
• Instance variables are variables that are specific to a
particular object. They are created when an object is
instantiated and destroyed when the object is garbage
collected.
30
Difference Between Class Variables
and Instance Variables in Java
• The main difference between class and instance
variables is that any class object can access class
variables. In contrast, instance variables can only be
accessed by the associated object.
31
Features of an instance variable
1. They are declared within the class but outside any method.
2. They are preceded by access specifier like private, public,
etc.
3. The value of an instance variable can be changed by calling
a setter method.
4. The value of an instance variable can be accessed by
calling a getter method.
5. It is not necessary to initialize an instance variable. It will
take the default for the respective data type.
32
• What is a static instance in Java?
Static instances are associated with the class rather than the object of
the class. They can be accessed by using the class name.
33
• Can we access instance members in the static method?
34
Instance method vs Static method
1. The instance method can access the instance methods and instance
variables directly.
2. The instance method can access static variables and static methods
directly.
3. Static methods can access the static variables and static methods
directly.
4. Static methods can’t access instance methods and instance
variables directly. They must use reference to object. And static
method can’t use this keyword as there is no instance for ‘this’ to
refer to.
35
Static Methods in Java
• Restrictions
• They can only call other static methods inside them.
• They must only access static data.
• They cannot refer to this or super in any way.
36
Static Methods Instance Methods
Static methods are associated with the class. Instance methods are associated with the objects.
Static methods can only access static attributes of the Instance methods can access all the attributes of the
class class.
A static method is declared with the static keyword. Instance methods do not require any keyword.
37
public class Checkstatic { public class Checkstatic {
public static void main(String[] args) { public static void main(String[] args) {
c2.setX(20); System.out.println(c1.x);
System.out.println(c1.getX()); c2.setX(20);
} System.out.println(c1.x);
c1.setX(30); c1.setX(30);
System.out.println(c2.getX()); System.out.println(c1.getX());
} }
} The static field Check.x should
}
be accessed in a static way
class Check{ class Check{
static int x=0; static int x=0;
Check(){ Check(){
x=10; x=10;
} }
38
public class Checkstatic {
We accessed in a static way
public class Checkstatic {
Since no instance object createded public static void main(String[] args) {
public static void main(String[] args) {
Check c1=new Check();
Check c2=new Check();
System.out.println(Check.x);
/*System.out.println(c1.x); syntax error :using set to change value
Check.setX(20); of x or get to return value of x
c2.setX(20);
System.out.println(Check.getX());
} System.out.println(c1.getX());
}
c1.setX(30);
class Check{ System.out.println(c2.getX());
static int x=0; }
}
Check(){
x=10; class Check{
} private static int x;
Check(int xvalue) Check(){
{ x =10;
x=xvalue; }
} Check(int xvalue)
public static void setX(int xvalue){ {
x=xvalue; x=xvalue;
} }
public static int getX(){ public void setX(int xvalue){
return x; x=xvalue;
} }
} public int getX(){
return x;
}
}
39
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
q public
The class, data, or method is visible to any class in any
package.
q private
The data or methods can be accessed only by the declaring
class.
The get and set methods are used to read and modify private
properties.(variables)
40
The private modifier restricts access to within a class, the default
modifier restricts access to within a package, and the public
modifier enables unrestricted access.
41
42
The default modifier on a class restricts access to within a package, and
the public modifier enables unrestricted access.
43
Why Data Fields Should Be private?
To protect data.
44
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier -radius: double The radius of this circle (default: 1.0).
-numberOfObjects: int The number of circle objects created.
CircleWithPrivateDataFields
TestCircleWithPrivateDataFields Run
45
public class TestPassObject { Passing Objects to Methods
/** Main method */
public static void main(String[] args) {
// Create a Circle object with radius 1
CircleWithPrivateDataFields myCircle = new CircleWithPrivateDataFields(1);
// Print areas for radius 1, 2, 3, 4, and 5.
int n = 5;
printAreas(myCircle, n);
Radius Area
1.0 3.141592653589793
2.0 12.566370614359172
3.0 28.274333882308138
4.0 50.26548245743669
5.0 78.53981633974483
Radius is 6.0n is 5
47
Array of Objects
Circle[] circleArray = new Circle[10];
49
Immutable( Cannot change) Objects and Classes
If the contents of an object cannot be changed once the object
is created, the object is called an immutable object and its class
is called an immutable class. If you delete the set method in
the Circle class in Listing 8.10, the class would be immutable
because radius is private and cannot be changed without a set
method.
A class with all private data fields and without mutators is not
necessarily immutable. For example, the following class
Student has all private data fields and no mutators, but it is
mutable.
50
Example public class BirthDate {
private int year;
public class Student { private int month;
private int id;
private BirthDate birthDate; private int day;
51
qThe this keyword is the name of a reference that refers to an object
itself. One common use of the this keyword is reference a class’s hidden
data fields.
qAnother common use of the this keyword to enable a constructor to
invoke another constructor of the same class.
53