You are on page 1of 17

Object Oriented Programming

10636212

Dr. Ashraf Armoush

© 2020 Dr. Ashraf Armoush

Chapter 03:

Object Oriented Programming

- Classes and Objects -

© 2020 Dr. Ashraf Armoush


Objects
• What is an Object?
– An object is a software bundle of related state and behavior.
• What possible states can this object be in?
• What possible behavior can this object perform?

– An object stores its state in fields or attributes (variables in some


programming languages) and exposes its behavior
through methods (functions in some programming languages).

Encapsulates data (attributes) and methods (behaviors)

– Software objects are often used to model the real-world objects that
you find in everyday life.
– Objects communicate through well-defined interfaces

• What is a Class?
– It is the blueprint from which individual objects are created.
© 2020 Dr. Ashraf Armoush , An-Najah National University 3

Example: Time Abstract Data Type


• Fields (Data to represent states):
– hour
– minute
– second

• Methods (behavior) :
– setTime(): set a new time value using universal time
– toUniversalString(): convert to String in universal-time
format
– toStandardString(): convert to String in standard-time format

© 2020 Dr. Ashraf Armoush , An-Najah National University 4


Implementing a Time Abstract Data Type with a Class

1 import java.text.DecimalFormat;
2
3 public class Time1 extends Object {
4 private int hour; // 0 - 23
5 private int minute; // 0 - 59
6 private int second; // 0 - 59
7 // Time1 constructor initializes each instance variable to zero;
8 // ensures that each Time1 object starts in a consistent state
9 public Time1()
10 {
11 setTime( 0, 0, 0 );
12 }
13 // set a new time value using universal time; perform
14 // validity checks on the data; set invalid values to zero
15 public void setTime( int h, int m, int s )
16 {
17 hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
18 minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
19 second = ( ( s >= 0 && s < 60 ) ? s : 0 );
20 }

© 2020 Dr. Ashraf Armoush , An-Najah National University 5

21 // convert to String in universal-time format


22 public String toUniversalString()
23 {
24 DecimalFormat twoDigits = new DecimalFormat( "00" );
25
26 return twoDigits.format( hour ) + ":" +
27 twoDigits.format( minute ) + ":" + twoDigits.format( second );
28 }
29
30 // convert to String in standard-time format
31 public String toStandardString()
32 {
33 DecimalFormat twoDigits = new DecimalFormat( "00" );
34
35 return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) + ":" +
36 twoDigits.format( minute ) + ":" + twoDigits.format( second ) +
37 ( hour < 12 ? " AM" : " PM" );
38 }
39
40 } // end class Time1

© 2020 Dr. Ashraf Armoush , An-Najah National University 6


• Every Java class must extend another class
– Time1 extends java.lang.Object
– If class does not explicitly extend another class
• class implicitly extends Object
• Class constructor
– Same name as class
– Initializes instance variables of a class object
– Called when program instantiates an object of that class
new ClassName( argument1, argument2, …, arugmentN );

– Can take arguments, but cannot return values


– Class can have several constructors, through overloading

© 2020 Dr. Ashraf Armoush , An-Najah National University 7

1 // Class TimeTest1 to exercise class Time1.


2 import javax.swing.JOptionPane;
3
4 public class TimeTest1 {
5
6 public static void main( String args[] )
7 {
8 Time1 time = new Time1(); // calls Time1 constructor
9
10 // append String version of time to String output
11 String output = "The initial universal time is: " +
12 time.toUniversalString() + "\nThe initial standard time is: " +
13 time.toStandardString();
14
15 // change time and append updated time to output
16 time.setTime( 13, 27, 6 );
17 output += "\n\nUniversal time after setTime is: " +
18 time.toUniversalString() +
19 "\nStandard time after setTime is: " + time.toStandardString();
20
21 // set time with invalid values; append updated time to output
22 time.setTime( 99, 99, 99 );
23 output += "\n\nAfter attempting invalid settings: " +
24 "\nUniversal time: " + time.toUniversalString() +
25 "\nStandard time: " + time.toStandardString();

© 2020 Dr. Ashraf Armoush , An-Najah National University 8


26 JOptionPane.showMessageDialog( null, output,
27 "Testing Class Time1", JOptionPane.INFORMATION_MESSAGE );
28
29 System.exit( 0 );
30
31 } // end main
32
33 } // end class TimeTest1

© 2020 Dr. Ashraf Armoush , An-Najah National University 9

• Class Time1 does not declare a constructor, so the


class has a default constructor that is supplied by the
compiler.
• Each instance variable implicitly receives the default
value 0 for an int.
• Instance variables also can be initialized when they
are declared in the class body, using the same
initialization syntax as with a local variable

© 2020 Dr. Ashraf Armoush , An-Najah National University 10


this Reference
• Every object can access a reference to itself with
keyword this.
• When a non-static method is called for a
particular object, the method’s body implicitly uses
keyword this to refer to the object’s instance
variables and other methods.
– Enables the class’s code to know which object should be
manipulated.
– Can also use keyword this explicitly in a non-static
method’s body.
• Can use the this reference implicitly and explicitly.

© 2020 Dr. Ashraf Armoush , An-Najah National University 11

Keyword this
1. Allows an object to public class A{
private int x;

refer to itself public A()


{
(as reference) int x; // local variable
x = 5; // modify the local variable
this.x = 7; // modify the member variable
– You can use the }
keyword this }

explicitly in a non-
static method’s
public class B{
body. private int x,y;
public B()
{ // invoke B constructor with 2 arguments.
this(0,0);

2. To call another class }


public B(int xValue, int yValue )

constructor {
x = xValue;

(as constructor) }
y= yValue;

© 2020 Dr. Ashraf Armoush , An-Najah National University 12


toString() method
• Class Object is the root of the class hierarchy.
• Every class has Object as a superclass.
• Class Objects has the method toString which returns a string
representation of the object.
public String toString();
• In general, the toString method returns a string that "textually
represents" this object.

• If you would like to display your object in specific text format,


you can rewrite (override) this method in your class
declaration.

© 2020 Dr. Ashraf Armoush , An-Najah National University 13

toString() method (cont.)


class A{
private int x;
public A(){ x = 10; }
public String toString() // override the toString method
{
String s = "Class A : x =" + x;
return s;
}
}
class B { C:\>java toStringTest
private int y; a1=Class A : x =10
public B (){ y = 10; } b1=B@3e25a5
}
public class toStringTest{
public static void main(String args[])
{
A a1;
B b1;
a1 = new A();
b1 = new B();
System.out.println("a1="+ a1); // invoke toString method of Class A
System.out.println("b1="+ b1); // invoke toString method of Class Object

}
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 14


Default and No-Argument Constructors
• Every class must have at least one constructor.
• If you do not provide any constructors in a class’s declaration, the
compiler creates a default constructor that takes no arguments
when it’s invoked.
• The default constructor initializes the instance variables to the
initial values specified in their declarations or to their default
values (zero for primitive numeric types, false for boolean
values and null for references).
• If your class declares constructors, the compiler will not
create a default constructor.
– In this case, you must declare a no-argument constructor if default
initialization is required.
– Like a default constructor, a no-argument constructor is invoked with
empty parentheses.

© 2020 Dr. Ashraf Armoush , An-Najah National University 15

Composition
A class can have references to objects of other classes
as members.

This is called composition and is sometimes referred to


as a has-a relationship.

Example: An AlarmClock object needs to know the


current time and the time when it’s supposed to sound
its alarm, so it’s reasonable to include two references to
Time objects in an AlarmClock object.

© 2020 Dr. Ashraf Armoush , An-Najah National University 16


Composition (cont.)
public class Date
{
private int month; // 1-12
private int day; // 1-31 based on month
private int year; // any year
private static final int[] daysPerMonth =
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// constructor: confirm proper value for month and day given the year
public Date(int month, int day, int year)
{
// check if month in range
if (month <= 0 || month > 12)
this.month = 1;
else
this.month = month;
// check if day in range for month
if (day <= 0 ||
(day > daysPerMonth[month] && !(month == 2 && day == 29)))
this.day = 1;
else
this.day = day;
this.year = year;
System.out.printf(
"Date object constructor for date %s%n", this);
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 17

Composition (cont.)
// return a String of the form month/day/year
public String toString()
{
return String.format("%d/%d/%d", month, day, year);
}
} // end class Date

© 2020 Dr. Ashraf Armoush , An-Najah National University 18


Composition (cont.)
public class Employee
{
private String firstName;
private String lastName;
private Date birthDate;
private Date hireDate;

// constructor to initialize name, birth date and hire date


public Employee(String firstName, String lastName, Date birthDate,
Date hireDate)
{
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
this.hireDate = hireDate;
}

// convert Employee to String format


public String toString()
{
return String.format("%s, %s Hired: %s Birthdate: %s",
lastName, firstName, hireDate, birthDate);
}
} // end class Employee

© 2020 Dr. Ashraf Armoush , An-Najah National University 19

Composition (cont.)
public class EmployeeTest
{
public static void main(String[] args)
{
Date birth = new Date(7, 24, 1990);
Date hire = new Date(3, 12, 2013);
Employee employee = new Employee("Ahmad", "Ali", birth, hire);

System.out.println(employee);
}
} // end class EmployeeTest

Date object constructor for date 7/24/1990


Date object constructor for date 3/12/2013
Ali, Ahmad Hired: 3/12/2013 Birthdate: 7/24/1990

© 2020 Dr. Ashraf Armoush , An-Najah National University 20


Garbage Collection
• Garbage collection
– Returns memory to the system
– The JVM performs automatic garbage collection to reclaim
the memory occupied by objects that are no longer used.
• When there are no more references to an object, the object is
eligible to be collected.
• Finalizer method protected void finalize()
{
– Returns resources to the system // finalization code here
}
– Java provides method finalize
• Defined in java.lang.Object
• Receives no parameters
• Returns void
• protected: to prevent access to finalize() by code defined
outside its class.

© 2020 Dr. Ashraf Armoush , An-Najah National University 21

Garbage Collection (cont.)


• A problem with method finalize is that the garbage
collector is not guaranteed to execute at a specified time.
• The garbage collector may never execute before a program
terminates.
• Thus, it’s unclear if, or when, method finalize will be
called.

• System.gc();
– Calls Java’s automatic garbage-collection mechanism

© 2020 Dr. Ashraf Armoush , An-Najah National University 22


final Instance Variables
• final keyword
– Indicates that variable is not modifiable
• Any attempt to modify final variable results in error
private final int INCREMENT = 5;
• Declares variable INCREMENT as a constant
– Enforces principle of least privilege

– If a final variable is not initialized, a


compilation error occurs.

© 2020 Dr. Ashraf Armoush , An-Najah National University 23

final Instance Variables (cont.)


public class Increment
{
private int total = 0; // total of all increments
private final int INCREMENT; // constant variable (uninitialized)

// constructor initializes final instance variable INCREMENT


public Increment( int incrementValue )
{
INCREMENT = incrementValue; // initialize constant variable (once)
} // end Increment constructor

// add INCREMENT to total


public void addIncrementToTotal()
{
total += INCREMENT;
} // end method addIncrementToTotal

// return String representation of an Increment object's data


public String toString()
{
return String.format( "total = %d", total );
} // end method toIncrementString
} // end class Increment

© 2020 Dr. Ashraf Armoush , An-Najah National University 24


final Instance Variables (cont.)
public class IncrementTest
{
public static void main( String args[] )
{
Increment value = new Increment( 5 );

System.out.printf( "Before incrementing: %s\n\n", value );

for ( int i = 1; i <= 3; i++ )


{
value.addIncrementToTotal();
System.out.printf( "After increment %d: %s\n", i, value );
} // end for
} // end main
} // end class IncrementTest

© 2020 Dr. Ashraf Armoush , An-Najah National University 25

Creating Packages
• Each class in the Java API belongs to a package that
contains a group of related classes.
• Packages are defined once, but can be imported into
many programs.
• Packages help programmers manage the complexity of
application components.
• Packages facilitate software reuse by enabling programs
to import classes from other packages, rather than
copying the classes into each program that uses them.
• Packages provide a convention for unique class names,
which helps prevent class-name conflicts.

© 2020 Dr. Ashraf Armoush , An-Najah National University 26


Creating Packages (cont.)
• Choose a unique package name and add a package
declaration to the source-code file for the reusable class
declaration.
– Every package name should start with your Internet domain name in
reverse order.
– After the domain name is reversed, you can choose any other names
you want for your package.
• The package declaration
package edu.najah.firstPackage;
• Placing a package declaration at the beginning of a Java
source file indicates that the class declared in the file is part of
the specified package.
• Only package declarations, import declarations and comments
can appear outside the braces of a class declaration.
• A Java source-code file must have the following order:
– a package declaration (if any), import declarations (if any), then class
declarations.

© 2020 Dr. Ashraf Armoush , An-Najah National University 27

Creating Packages (cont.)


• Compile the class so that it’s placed in the appropriate
package directory.

• javac command-line option -d causes the javac compiler


to create appropriate directories based on the class’s package
declaration.
– The option also specifies where the directories should be
stored.

• Example:
javac -d . Time1.java
• specifies that the first directory in our package name should
be placed in the current directory (.).

© 2020 Dr. Ashraf Armoush , An-Najah National University 28


Enumerations (enum Types )
• An enum type is a type whose fields consist of a fixed set of
constants.
• In Java, you can define an enum type by using the enum keyword

public enum Day{


SATURDAY, SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY
}

– Like classes, all enum types are reference types.


– enum types are implicitly final, because they declare constants .
– enum constants are implicitly static.
– Any attempt to create an object of an enum type with operator
new results in a compilation error.
• For every enum, the compiler generates the static method values() that
returns an array of the enum’s constants in the order they were declared.
© 2020 Dr. Ashraf Armoush , An-Najah National University 29

Enumerations (cont.)
import java.util.EnumSet;

public class EnumTest{

public static void main( String args[] )


{
Day meetingDay = Day.SUNDAY;

System.out.println( "The meeting will be on "+ meetingDay);

// print all days in enum Day


System.out.println("\nDisplay all days in enum Day:" );

for ( Day day : Day.values() )


System.out.println( day );

// print the first four days


System.out.println( "\nDisplay a range of enum constants:\n");

for ( Day day : EnumSet.range( Day.SATURDAY, Day.TUESDAY ) )


System.out.println( day );
} // end main
}

© 2020 Dr. Ashraf Armoush , An-Najah National University 30


Enumerations (cont.)
c:\enumTest>java EnumTest

The meeting will be on SUNDAY

Display all days in enum Day:


SATURDAY
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY

Display a range of enum constants:

SATURDAY
SUNDAY
MONDAY
TUESDAY

c:\enumTest>

© 2020 Dr. Ashraf Armoush , An-Najah National University 31

Enumerations (cont.)
public enum Book
{
• You can declare instance // declare constants of enum type
JHTP("Java How to Program", "2015"),
variables, a constructor CHTP("C How to Program", "2013"),
and methods in an enum IW3HTP("Internet & World Wide Web How to Program","2012"),
CPPHTP("C++ How to Program", "2014"),
type. VBHTP("Visual Basic How to Program", "2014"),
CSHARPHTP("Visual C# How to Program", "2014");
// instance fields
private final String title;
• Each enum constant is private final String copyrightYear;
// enum constructor
optionally followed by Book(String title, String copyrightYear)
arguments which are {
this.title = title;
passed to the enum this.copyrightYear = copyrightYear;
}
constructor.
// accessor for field title
public String getTitle()
{
return title;
}

// accessor for field copyrightYear


public String getCopyrightYear()
{
return copyrightYear;
}
} // end enum Book
© 2020 Dr. Ashraf Armoush , An-Najah National University 32
Enumerations (cont.)

import java.util.EnumSet;

public class EnumTest


{
public static void main(String[] args)
{
System.out.println("All books:");

// print all books in enum Book


for (Book book : Book.values())
System.out.printf("%-10s%-45s%s%n", book,
book.getTitle(), book.getCopyrightYear());

System.out.printf("%nDisplay a range of enum constants:%n");

// print first four books


for (Book book : EnumSet.range(Book.JHTP, Book.CPPHTP))
System.out.printf("%-10s%-45s%s%n", book,
book.getTitle(), book.getCopyrightYear());
}
} // end class EnumTest

© 2020 Dr. Ashraf Armoush , An-Najah National University 33

Enumerations (cont.)
All books:
JHTP Java How to Program 2015
CHTP C How to Program 2013
IW3HTP Internet & World Wide Web How to Program 2012
CPPHTP C++ How to Program 2014
VBHTP Visual Basic How to Program 2014
CSHARPHTP Visual C# How to Program 2014

Display a range of enum constants:


JHTP Java How to Program 2015
CHTP C How to Program 2013
IW3HTP Internet & World Wide Web How to Program 2012
CPPHTP C++ How to Program 2014

© 2020 Dr. Ashraf Armoush , An-Najah National University 34

You might also like