0% found this document useful (0 votes)
9 views

09slide Comp2311

Uploaded by

aq610689
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

09slide Comp2311

Uploaded by

aq610689
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

COMPUTER SCIENCE DEPARTMENT FACULTY OF ENGINEERING AND TECHNOLOGY

OBJECT-ORIENTED PROGRAMMING
COMP2311
Instructor :Murad Njoum
Office : Masri322
1

Chapter 9 Objects and Classes - Revision


OO Programming Concepts
Object-oriented programming (OOP) involves programming
using objects. An object represents an entity in the real
world that can be distinctly identified. For example, a
student, a desk, a circle, a button, and even a loan can all be
viewed as objects. An object has a unique identity, state, and
behaviors. The state of an object consists of a set of data fields
(also known as properties) with their current values. The
behavior of an object is defined by a set of methods.

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

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double
getPerimeter(): double
setRadius(newRadius:
double): void

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125

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);
}
}

Compile error: variable not


initialized
14
Differences between Variables of
Primitive Data Types and Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

15
Garbage Collection,

TIP: If you know that an object is no longer needed,


you can explicitly assign null to a reference variable for
the object. The JVM will automatically collect the
space if the object is not referenced by any variable.

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

java.util.Date date = new java.util.Date();


System.out.println(date.toString());

displays a string like Sun Mar 09 13:50:19 EST


2003.

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.

• Instance variables are specific to a particular instance


of a class.
• Class variables are usually shared by all instances of
the class in java. In other words, they belong to the
class, not any particular class instance.

21
Example:
public class Employee {
public String Name; // Name is an instance variable
with public access modifier

private int salary ; // salary is an instance


variable with private access modifier.

public static String company; // Company is not an


instance variable as it is Static, and the value it
holds is class specific but not instance.
}
22
What is an Instance Variable in Java?
• Instance variables are specific to a particular instance
of a class. For example, each time you create a new
class object, it will have its copy of the instance
variables.

• Instance variables are the variables that are declared


inside the class but outside any method.
• Instance variables are specific to each instance of a
class. This means that each object in a Java program
has its copy of the instance variables defined for that
class.

23
Instance
Variables, and Methods

• Instance variables belong to a specific instance.


Instance methods are invoked by an instance of the class.

24
Static Variables, Constants, and Methods

Static variables are shared by all the instances of the class.

Static methods are not tied to a specific instance (object).


Static constants are final variables shared by all the instances of the
class.

To declare static variables, constants, and methods, use


the static modifier.
25
Static Variables, Constants,
and Methods, cont.

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; }

/** Construct a circle with radius 1 */ /** Return numberOfObjects */


CircleWithStaticMembers() { static int getNumberOfObjects() {
radius = 1.0; return numberOfObjects;
numberOfObjects++; }
}
/** Return the area of this circle */
double getArea() {
return radius * radius * Math.PI;
}
} 27
Static Variable
1. It is a variable which belongs to the class and not to the instance
(object).
2. Static variables are initialized only once, at the start of the
execution.
Static variables will be initialized first, before the initialization of any
instance variables.
3. A single copy to be shared by all instances of the class.
4. A static variable can be accessed directly by the class name and
doesn’t need any object.

Syntax : < class - name>.<static - variable - name>


28
Static Method
1. It is a method which belongs to the class and not to the instance (object).
2. A static method can access only static data. It can not access non-static
data (instance variables).
3. A static method can call only other static methods and can not call a non-
static method from method inside.
4. A static method can be accessed directly by the class name and doesn’t
need any create an instance (object) to access it.
Syntax : < class - name>.<static - method - name>(..)
5. A static method cannot refer to “this” or “super” keywords in anyway.

Note: main method is static, since it must be accessible for an


application to run, before any instantiation takes place.

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.

• Static variables are the variables that are shared by all


objects of a class. They are created when the class is
loaded and destroyed when it is unloaded.

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.

• Instance variables can be initialized when you create the


object or set their values later using a setter method.
Contrast this with class variables (must be initialized),
which are shared by all class objects.

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.

• What is the difference between static methods vs instance methods


in Java?
Static members are independent of the objects of the class, while
instance members depend on the object.

• What is the instance method?


The instance method is a method that is declared in the class without
using the static keyword. It can be called with the help of the object
of the class.

33
• Can we access instance members in the static method?

No, we cannot directly access the instance variables within a static


method because a static method can only access static members.

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 can be called without the object of the


Instance methods require an object of the class.
class.

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.

The instance method exists as multiple copies


The static method will exist as a single copy for a class.
depending on the number of instances of the class.

37
public class Checkstatic { public class Checkstatic {

public static void main(String[] args) { public static void main(String[] args) {

Check c1=new Check(); Check c1=new Check();


Check c2=new Check(); Check c2=new Check();

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;
} }

Check(int xvalue) Check(int xvalue)


{ {
x=xvalue; x=xvalue;
} }
public void setX(int xvalue){ public void setX(int xvalue){
x=xvalue; x=xvalue;
} }
public int getX(){ public int getX(){
return x; return x;
}} }}

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.

To make code easy to maintain.

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.

+Circle() Constructs a default circle object.


+Circle(radius: double) Constructs a circle object with the specified radius.
+getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getNumberOfObjects(): int Returns the number of circle objects created.
+getArea(): double Returns the area of this circle.

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);

// See myCircle.radius and times


System.out.println("\n" + "Radius is " + myCircle.getRadius());
System.out.println("n is " + n);
}
/** Print a table of areas for radius */
public static void printAreas(CircleWithPrivateDataFields c, int times) {
System.out.println("Radius \t\tArea");
while (times >= 1) {
System.out.println(c.getRadius() + "\t\t" + c.getArea());
c.setRadius(c.getRadius() + 1);
times--;
}
} 46
}
Passing Objects to Methods
qPassing by value for primitive type value (the value
is passed to the parameter)
qPassing by value for reference type value (the
value is the reference to the object)

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];

An array of objects is actually an array of


reference variables. So invoking
circleArray[1].getArea() involves two
levels of referencing as shown in the next
figure. circleArray references to the entire
array. circleArray[1] references to a Circle
object.
48
Array of Objects, cont.
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;

public Student(int ssn, public BirthDate(int newYear,


int year, int month, int day) { int newMonth, int newDay) {
id = ssn;
birthDate = new BirthDate(year, month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId() { }
return id;
}
public void setYear(int newYear) {
public BirthDate getBirthDate() { year = newYear;
return birthDate; }
}
} }

public class Test {


public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}

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.

Remember : . A static method cannot refer to “this”


or “super” keywords in anyway.
52
Calling Overloaded Constructor
public class Circle {
private double radius;

public Circle(double radius) {


this.radius = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an instance represented by this,
which is normally omitted

53

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy