Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 27

CHAPTER 8 OBJECTS AND

CLASSES

8.6 Using Classes from the Java Library


8.6.1 The Date Class
8.6.2 The Random Class
8.7 Static Variables, Constants, and Methods
8.8 Visibility Modifiers (public, default, private)
8.9 Data Field Encapsulation (set and get Methods)

1
8.6 USING CLASSES FROM THE JAVA LIBRARY

• The Java API contains a rich set of classes for


developing Java programs.
• In CSCI250 we have used more than one class from the
library such as System, Math, Scanner, and String.
• This section gives some examples of the classes in the
Java library.

2
8.6.1 THE DATE CLASS
The Date class is found in the util package in the Java library.
To use we write import java.util.Date;
You can use the Date class to create an instance (object) 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.

3
THE DATE CLASS EXAMPLE
For example, the following code

Date date = new Date();


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

displays a string like Mon Mar 23 20:50:19 EST 2020.

4
8.6.2 THE RANDOM CLASS
the Random class found also in the util package is used to
generate random values of different types as shown in the
table below.

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. 5
THE RANDOM CLASS EXAMPLE
To use the Random class you need to first import it:
import java.util.Random;

Random r = new Random();

int x = r.nextInt(); // x could be any integer value

int y = r.nextInt(10);
// y could be any integer value between 0 inclusive and 10 exclusive (i.e. between 0 and 9)

double z = r.nextDouble();
// z could be any double value between 0.0 inclusive and 1.0 exclusive

boolean flag = r.nextBoolean(); // flag could be either false or true


6
8.7 STATIC VARIABLES, CONSTANTS, AND
METHODS
Static variables versus instance variables

• An instance of a class means an object of that class.

• An instance variable (instance data field) also known as non static


variable is tied to a specific instance (object) of the class; it is not
shared among objects of the same class. The data field radius in the
Circle class is known as an instance variable.

• A static variable (static data field) is a data field shared by all objects
of the class.
7
WHY DO WE USE STATIC VARIABLES?
• If you want all the instances (objects) of a class to share data, use static variables, also known
as class variables. A static variable stores its value in a memory location common to all
objects of the class.

• Because of this common location, if one object changes the value of a static variable, all
objects of the same class are affected.

• An example of when do we use static variable is if we need a counter to keep track of how
many objects are created.

• To declare static variables, constants, and methods, use the static modifier.

8
HOW TO ACCESS STATIC
VARIABLES
Remember that we can access an instance data
such as radius via a reference variable as in
myCircle.radius

Assume the class Circle has a static data named


numberOfObjects. To access this static data we
can do that either using a reference variable as in
myCircle.numberOfObjects
or using the class name as in
Circle.numberOfObjects 9
STATIC METHODS

A static method is a method that returns a static data field.

An instance method (non static method) is invoked (called) using an instance (object) of
the class.
Example: myCircle.getArea( ); // objectReference.method( )

A static method can be called without creating an instance of the class. It can be invoked
by either an instance (object) of the class or using the class name. Assume we have a
static method named getNumberOfObjects( ) that has the following header:
public static int getNumberOfObjects ( )
Then we can call it in either one of the following two ways:
myCircle.getNumberOfObjects( ); // objectReference.method( )
or
Circle.getNumberOfObjects( ); // class.method( )

10
STATIC METHODS VERSUS INSTANCE METHODS

• An instance method can invoke an instance or static


method and access an instance or static data field.
• A static method can invoke a static method and access a
static data field.
• A static method cannot invoke an instance method or
access an instance data field.

11
STATIC CONSTANTS

Static constants are final variables shared by all the


instances of the class.

Constants should be declared as final static. For


example, the constant PI in the Math class is
defined as:
final static double PI = 3.14159265358979323846;

12
CIRCLE CLASS WITH A STATIC
DATA
public class Circle {

double radius ; // instance data (each Circle object has its own radius)
static int numberOfObjects = 0; // static data (shared by all Circle objects)

public Circle(double r) {
radius = r;
numberOfObjects++; // increase by 1 each time an object is created
}
public double getArea( ) { // instance method
return radius * radius * Math.PI;
}
public static int getNumberOfObjects( ) { // static method
return numberOfObjects;
}
13
} // end class Circle
APPLICATION / DRIVER CLASS
public class TestCircle {

public static void main(String[] args) {

System.out.println("Before creating objects");

System.out.println("The number of Circle objects is " +


Circle.numberOfObjects);

Circle c1 = new Circle (1);

System.out.println("After creating c1");

System.out.println ("The number of Circle objects is " +


c1.numberOfObjects );
System.out.println ("The number of Circle objects is " +
Circle.numberOfObjects);

Circle c2 = new Circle (5);

System.out.println("After creating c2");

System.out.println ("The number of Circle objects is " +


c1.numberOfObjects);

System.out.println ("The number of Circle objects is " +


c2.numberOfObjects);

System.out.println ("The number of Circle objects is " +


Circle.numberOfObjects ); 14
}

}
OUTPUT
Before creating objects
The number of Circle objects is 0
After creating c1
The number of Circle objects is 1
The number of Circle objects is 1
After creating c2
The number of Circle objects is 2
The number of Circle objects is 2
The number of Circle objects is 2 15
UML DIAGRAMS

The static data and the static methods are underlined in the UML
Diagram.

Instance variables belong to the instances and have memory storage


independent of one another. Static variables are shared in memory by
all the instances of the same class. 16
8.8 VISIBILITY MODIFIERS

Visibility modifiers can be used to specify the visibility of a class


and its members.

• You can use the public visibility modifier for classes, methods,
and data fields to denote that they can be accessed from any other
classes.

• The private modifier makes methods and data fields accessible


only from within its own class.

• If no visibility modifier is used, then by default the classes,


methods, and data fields are accessible by any class in the same17
package. This is known as package-access.
8.8 (CONTINUED)

Summary of visibility modifiers:


• public
The data field or method is visible to any class in any package.
• private
The data or method can be accessed only by the declaring class.
• default (not public and not private)
By default, the data or method can be accessed by any class in
the same package.

Note: public and private are keywords.

18
8.8 (CONTINUED)
In the example below the data field x and the method m1( )
have public visibility, z and m3( ) have private visibility, and
y and m2( ) have default visibility.
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }

The private modifier restricts access to within a class, the default


modifier restricts access to within a package, and the public 19
modifier enables unrestricted access.
8.8 (CONTINUED)

Usually the data fields should be private and the


methods should be public.

Using the modifiers public and private on local


variables would cause a compile error.

20
8.9 DATA FIELD ENCAPSULATION

To prevent direct modifications of data fields, you should declare


the data fields private, using the private modifier. This is known
as data field encapsulation.

Why should data fields be private?


To protect data from being changed in an invalid way. For
example, assigning the radius a negative value.

21
8.9 (CONTINUED)
The need for get and set methods:

• A private data field cannot be accessed by an object


from outside the class that defines the private field.
However, a program often needs to retrieve and
modify a data field.

• To make a private data field accessible, provide a


get method to return its value.

• To enable a private data field to be updated, provide


22
a set method to set a new value.
8.9 (CONTINUED)
• A get method is referred to as a getter (or accessor) and
a set method is referred to as a setter (or mutator).

• A get method has the following signature:


public returnType getPropertyName()

• If the returnType is boolean, the get method will have


the following signature:
public boolean isPropertyName()

• A set method has the following signature:


23
public void setPropertyName(dataType propertyValue)
EXAMPLE OF
DATA FIELD ENCAPSULATION
Let’s create a new circle class with a private data-field radius and
its associated accessor (getter) and mutator (setter) methods.
In the UML diagram, the + sign means public and the – sign
means private.
Circle
The - sign indicates
private modifier -radius: double The radius of this circle.

+Circle(radius: double) Constructs a circle object with the specified radius.


The + sign indicates
public modifier +getRadius(): double Returns the radius of this circle.
+setRadius(radius: double): void Sets a new radius for this circle.
+getArea(): double Returns the area of this circle.

24
CLASS CIRCLE WITH PRIVATE DATA AND
GETTER AND SETTER METHODS
public class Circle {

private double radius;

public Circle (double newRadius) {

if (newRadius >= 0)

radius = newRadius;

else

radius = 0;

public double getRadius() {

return radius;

public void setRadius(double newRadius) {

if (newRadius >= 0)

radius = newRadius;

else

radius = 0;

public double getArea() {

return radius * radius * Math.PI; 25


}
} // end class
ROLE OF THE GETTER AND
SETTER METHODS
• The getRadius() method returns the radius, and the
setRadius(newRadius) method sets a new radius for the
object. If the new radius is negative, 0 is set as the radius
for the object.
• Since these methods are the only ways to read and modify
the radius, you have total control over how the radius
property is accessed.

26
APPLICATION / DRIVER CLASS
public class TestCircle {
public static void main(String[] args) {

Circle c1 = new Circle (5.0);


System.out.println("Area of the circle of radius " +
c1.getRadius() + " is " + c1.getArea());

// Change the radius of c1 to 10.0


c1.setRadius(10.0);
System.out.println("Area of the circle of radius " +
c1.getRadius() + " is " + c1.getArea());
}
}

Note: if you write c1.radius = -2; in the main method then you will get a27
syntax error since radius is private in the class.

You might also like