Documentos de Académico
Documentos de Profesional
Documentos de Cultura
By
Encapsulation
Objects hide their functions
(methods) and data (instance
variables)
Inheritance
Each subclass inherits all variables car Super class
of its superclass
auto-
manual Subclasses
Polymorphism matic
4
Database System Concepts 3.4 ©Silberschatz, Korth and Sudarshan
Applets
There are some important differences between an applet and a
standalone Java application, including the following:
An applet is a Java class that extends the java.applet.Applet
class.
A main() method is not invoked on an applet, and an applet class
will (typically) not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the
code for the applet is downloaded to the user’s machine.
A user must have a JVM on his or her machine. The JVM can be
either a plug-in of the Web browser or a separate runtime
environment.
The JVM on the user’s machine creates an instance of the applet
class and invokes various methods during the applet’s lifetime.
5
Database System Concepts 3.5 ©Silberschatz, Korth and Sudarshan
Understanding the Polymorphism
Polymorphism: Introduction
What is Polymorphism & Why ?
Method overriding & Method over loading
Class references to Child Objects ?
Instantiation of Objects: Overview
Understanding the references
Polymorphic parameters
Casting references
Instanceof Keyword
Benefits of Polymorphism
Extensibilty
Heterogeneous Collection
6
Database System Concepts 3.6 ©Silberschatz, Korth and Sudarshan
Polymorphism
The term Polymorphism (poly, meaning many or multiple,
and morph,
morph meaning shapes or forms) in OOP refers to the
ability of an object to have many forms,
forms which is a direct
result of inheritance.
An object takes on many forms because an object can be
treated as a child type, a parent type,
type a grandparent type,
and so on up the hierarchy tree.
When we discussed inheritance, we discussed how the is a
relationship is used to determine if your inheritance is a
good design. The is a relationship is also helpful when
learning polymorphism.
With Polymorphism, we can add new classes with little or
no modification in general portions of the program, as long
as the new classes are part of the inheritance hierarchy that
the program processes generically.
7
Database System Concepts 3.7 ©Silberschatz, Korth and Sudarshan
Polymorphism: Methods & Objects
8
Database System Concepts 3.8 ©Silberschatz, Korth and Sudarshan
Polymorphism
• Ex. Bird, Person and Fish are
child classes of Animal.
• Suppose we wish to create a
move()
program that simulates the
movement of several types of
animals.
• Each subclass Bird, Fish and
Person extends the
Superclass Animal, which
contain a method move()
move() move()
maintains an animal’s current
location as x-y coordinates.
• Each subclass implements
method move & overrides the
move() method in its own way
move()
11
Database System Concepts 3.11 ©Silberschatz, Korth and Sudarshan
Java : OOM Characteristics & Implementations
Inheritance, Polymorphism & Abstraction
Interface: Java Implementation & Applications
Java API and Applets
User Defined Interfaces
Design Principles:
Principles GoF & Liskov’s Principles 12
Database System Concepts 3.12 ©Silberschatz, Korth and Sudarshan
The 03 principles of OOM works together
Inheritance , Encapsulation
and Polymorphism when
properly applied it can produce
a programming environment
that supports the development
of far more robust & scalable
programs than does the
process-oriented model.
Disadvantages:
- Breaks encapsulation, since it exposes a subclass to
implementation details of its superclass
- "White-box" reuse, since internal details of superclasses
are often visible to subclasses
- Subclasses may have to be changed if the implementation
of the superclass changes
- Implementations inherited from superclasses can not be
changed at runtime
17
Database System Concepts 3.17 ©Silberschatz, Korth and Sudarshan
Abstraction
The Employee class is a perfect example of a
class that really does not need to be instantiated
from a design perspective.
Notice that the employee did not have any
information about how much it is paid, and its
computePay() method simply returns 0.0.
It is safe to say that no employee of our company
would want to be strictly an Employee object (and
not one of the child class types).
We can make it so that no one can instantiate an Employee
object, by declaring the Employee class abstract.
This has no effect on how the fields, methods, and constructors
behave.
18
Database System Concepts 3.18 ©Silberschatz, Korth and Sudarshan
Abstraction
.
The only result of making Employee abstract is that we can
no longer create an instance of Employee.
Que.Look at example, the following would new
statement compile ?
21
Database System Concepts 3.21 ©Silberschatz, Korth and Sudarshan
Abstract Methods
public abstract class Employee
{
private String name;
private String address;
private int number;
public abstract double computePay();
//Remainder of class definition
}
22
Database System Concepts 3.22 ©Silberschatz, Korth and Sudarshan
Abstraction
Tony Hoare: “Abstraction arises from a recognition of
similarities between certain objects, situations, or processes
in the real world, and the decision to concentrate upon those
similarities and to ignore for the time being the differences.”
12/08/21 25
Database System Concepts 3.25 ©Silberschatz, Korth and Sudarshan
An Overview of Interfaces
Interfaces form a contract between the class and the outside world, and
this contract is enforced at build time by the compiler.
If our class claims to implement an interface, all methods defined by
that interface must appear in its source code before the class will
successfully compile.
An interface is similar to a class in the following ways:
12/08/21 26
Database System Concepts 3.26 ©Silberschatz, Korth and Sudarshan
Interface
However, an interface is different from a class in several ways,
including:
■■ We cannot instantiate an interface.
■■ An interface does not contain any constructors.
■■ All of the methods in an interface are abstract.
■■ An interface cannot contain instance fields. The
only fields that can appear in an interface must be
declared both static and final.
■■ An interface is not extended by a class; it is
implemented by a class.
■■ An interface can extend multiple interfaces.
12/08/21 27
Database System Concepts 3.27 ©Silberschatz, Korth and Sudarshan
Interface
Interface can be used to define a generic template and then one or
more abstract classes to define partial implementations of the
interface.
Interfaces just specify the method declaration (implicitly public and
abstract) and can only contain fields (which are implicitly public static
final).
Interface definition begins with a keyword interface. An interface
like that of an abstract class cannot be instantiated.
Multiple Inheritance is allowed when extending interfaces i.e. one
interface can extend none, one or more interfaces. Java does not
support multiple inheritance, but it allows you to extend one class
and implement many interfaces.
If a class that implements an interface does not define all the
methods of the interface, then it must be declared abstract and
the method definitions must be provided by the subclass that
extends the abstract class.
12/08/21 28
Database System Concepts 3.28 ©Silberschatz, Korth and Sudarshan
Interfaces
Interfaces have many uses and benefits;
12/08/21 29
Database System Concepts 3.29 ©Silberschatz, Korth and Sudarshan
Interface
An interface is implicitly abstract.
abstract We do not need to use the
abstract keyword when declaring an interface (although it is
acceptable to use it).
■■ Each method in an interface is also implicitly
abstract, so the abstract keyword is not needed.
You can explicitly declare a method in an interface as
abstract, but typically the abstract keyword is left off.
■■ Methods in an interface are implicitly public. It is
common practice to use the public keyword when
writing an interface, but if you do not explicitly declare
a method in an interface as public, it will be public
anyway.
12/08/21 30
Database System Concepts 3.30 ©Silberschatz, Korth and Sudarshan
Interface: Summary…
An interface is not a class.
Writing an interface is similar to writing a class, but they are
two different concepts.
A class describes the attributes and behaviors of an object.
An interface contains behaviors that a class implements.
One benefit of using interfaces is that they simulate multiple
inheritance.
All classes in Java (other than java.lang.Object -- the root
class of the Java type system) must have exactly one base
class; multiple inheritance of classes is not allowed.
Furthermore, a Java class may implement, and an
interface may extend, any number of interfaces; however
an interface may not implement an interface.
12/08/21 31
Database System Concepts 3.31 ©Silberschatz, Korth and Sudarshan
Difference Between Interface and Abstract
Class
Main difference is methods of a Java interface are implicitly
abstract and cannot have implementations.
A Java abstract class can have instance methods that
implements a default behavior.
Variables declared in a Java interface is by default final.
12/08/21 32
Database System Concepts 3.32 ©Silberschatz, Korth and Sudarshan
Difference
An interface can extend another Java interface only, an
abstract class can extend another Java class and implement
multiple Java interfaces.
A Java class can implement multiple interfaces but it can
extend only one abstract class.
Interface is absolutely abstract and cannot be instantiated;
12/08/21 33
Database System Concepts 3.33 ©Silberschatz, Korth and Sudarshan
Mid Sem evaluation
The Valued copies of Mid Semester Exam can be
seen on Saturday 10:AM to 5;00 PM at Room no.
4220 (CC-2).
12/08/21 34
Database System Concepts 3.34 ©Silberschatz, Korth and Sudarshan
Java : OOM Characteristics & Implementations
Inheritance, Polymorphism & Abstraction
Interface: Java Implementation & Applications
Java API and Applets
User Defined Interfaces
Design Principles:
Principles GoF & Liskov’s Principles 35
Database System Concepts 3.35 ©Silberschatz, Korth and Sudarshan
Interface: Summary…
An interface is not a class.
Writing an interface is similar to writing a class, but they are
two different concepts.
A class describes the attributes and behaviors of an object.
An interface contains behaviors that a class implements.
One benefit of using interfaces is that they simulate multiple
inheritance.
All classes in Java (other than java.lang.Object -- the root
class of the Java type system) must have exactly one base
class; multiple inheritance of classes is not allowed.
Furthermore, a Java class may implement, and an
interface may extend, any number of interfaces; however
an interface may not implement an interface.
12/08/21 36
Database System Concepts 3.36 ©Silberschatz, Korth and Sudarshan
Multiple inheritance …
References can be explored in multiple inheritance, Ex.:
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d; Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap.
12/08/21 38
Database System Concepts 3.38 ©Silberschatz, Korth and Sudarshan
Common Interfaces of Java API
12/08/21 40
Database System Concepts 3.40 ©Silberschatz, Korth and Sudarshan
Comparable: Java contains several comparison operators
(e.g., <, <=, >, >=, ==,!=) that allows to compare primitive values.
However, these operators cannot be used to compare the contents of
objects. Interface Comparable is used to allow objects of a class that
implements the interface to be compared to one another. The
interface contains one method, compareTo, that compares the object
that calls the methods to the objects passed as an argument to the
method. Classes must implement compareTo such that it returns a
value indicating whether the object on which it is invoked is less
than (- integer return value), equal to (0 return value) or greater than
(+ integer return value) the object passed as an argument using any
criteria specified by the programmer.
48
Database System Concepts 3.48 ©Silberschatz, Korth and Sudarshan
User defined interface
Let’s work through an example where you write your
own interface and then a class that implements it. Open
your text editor and follow along through the following
steps.
Write the Interface Source Code
Start by writing the .java file for an interface named
Paintable. The interface will represent any object that
can be painted onscreen. It will contain a single method
named paint().
Type in the Paintable interface.
Compile the Interface
Save the source code file in a new directory named
c:\interfaces\display.
Create this directory, and save the file there as
Paintable.java. Interfaces are compiled the same way
as classes, using the javac compiler.
12/08/21 49
Database System Concepts 3.49 ©Silberschatz, Korth and Sudarshan
Implementing an Interface
When a class implements an interface, you can think of the class
as signing a contract, agreeing to perform the specific behaviors of
the interface.
If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.
More specifically, when a class implements an interface, the class
has two options:
■■ Implement all of the methods in the interface
■■ Be declared as abstract
A class uses the implements keyword to implement an interface.
The implements keyword appears in the class declaration
following the extends portion of the declaration.
The format for implements looks similar to:
public class ClassName extends ParentClassName
implements InterfaceName
12/08/21 50
Database System Concepts 3.50 ©Silberschatz, Korth and Sudarshan
Class that Implements Paintable
In this step, we will write a class
named Rectangle that implements
the Paintable interface.
Open your text editor, and type in
the class shown in Figure
Notice that the Rectangle class
declares that it implements
Paintable, but it does not contain
the paint() method.
Save the Rectangle class in your
c:\interface directory.
Compile Rectangle.java using
javac.
What will happen ?
12/08/21 51
Database System Concepts 3.51 ©Silberschatz, Korth and Sudarshan
Implementing Paintable
52
Database System Concepts 3.52 ©Silberschatz, Korth and Sudarshan
Implementing Paintable
Let’s add the paint() method to the
Rectangle class so that it compiles
properly. Add the paint() method
shown in Fig, and compile your
Rectangle class again.
12/08/21 53
Database System Concepts 3.53 ©Silberschatz, Korth and Sudarshan
Write a Class That Uses Paintable
Write the MyPainter class in
Figure, which contains a
paintAnything() method.
The paintAnything() method can
paint any object of type
Paintable.
Within main(), a MyPainter object
paints a Rectangle object passed
in to the paintAnything() method.
Type in the MyPainter program
and save it in your
c:\interface directory.
directory
Run the MyPainter program, and
you should show the output in
next Lecture.
12/08/21 54
Database System Concepts 3.54 ©Silberschatz, Korth and Sudarshan
Using Interfaces
Interfaces have two equally important but different usages:
■■ An interface can be used to expose the methods of a
class, allowing users of the class to interface with objects of
the class via the methods in the interface.
■■ An interface can be used to force certain behaviors on a
class.
These two usages create a wealth of design opportunities for
Java applications.
Being able to expose methods of a class using an interface is
used extensively in distributed computing, which includes
technologies such as RMI (Remote Method Invocation), CORBA,
and Web Services.
12/08/21 55
Database System Concepts 3.55 ©Silberschatz, Korth and Sudarshan
Why Distributed Applications?
Data is distributed
Copyright © 1998
Purple Technology,
Database System Concepts 3.56 ©Silberschatz, Korth and Sudarshan
What is CORBA?
Common Object Request Broker Architecture
Communication infrastructure for distributed
objects
Allows a heterogeneous, distributed collection
of objects to collaborate transparently.
CORBA loves Java !
CORBA provides a platform-independent, language-independent
way to write applications that can invoke objects that live across
the room or across the planet. Java is an object-oriented
language that's ideal for writing the clients and servers living on
the Object Bus
Copyright © 1998
Purple Technology,
Database System Concepts 3.57 ©Silberschatz, Korth and Sudarshan
CORBA Criticism
While CORBA promised to deliver much in the way code was
written and software constructed, it has been the subject of
much criticism.
Some of the failures were due to the implementations and the
process by which CORBA was created as a standard, others
reflect problems in the politics and business of implementing a
software standard.
These problems led to a significant decline in CORBA use and
adoption in new projects and areas.
12/08/21 58
Database System Concepts 3.58 ©Silberschatz, Korth and Sudarshan
Project Team : Diverse Software requirement
P r o je c t L e a d e r
D e v e lo p e r s DBAs
12/08/21 60
Database System Concepts 3.60 ©Silberschatz, Korth and Sudarshan
OOM & GUI
Typical GUI providing user friendly environment comprises
of ;
Buttons,
Menus
Combo boxes &
Bars: Title Bar, Menu Bar & Scroll Bar.
12/08/21 61
Database System Concepts 3.61 ©Silberschatz, Korth and Sudarshan
GUI with Java
Using OOP (Inheritance) in Java
GUI : AWT & Swing
Creating Window: GUI Coordinate systems
Import Classes
OOP characteristics on AWT & Swing
Instantiate Frame Object
12/08/21 62
Database System Concepts 3.62 ©Silberschatz, Korth and Sudarshan
User Interface
Sun had used a logical and object-oriented design for
creating a GUI and handling its events.
There are two APIs for creating GUI applications in Java:
Swing and AWT (Abstract Windowing Toolkit).
When Java was first released in 1995, it contained a GUI API
: AWT.
AWT API contained classes like
63
Database System Concepts 3.63 ©Silberschatz, Korth and Sudarshan
GUI: AWT & Swing
AWT components are referred to as heavyweight components
because their implementation relies heavily on the underlying
operating system.
The look and feel of AWT components depend on the
platform the program is running on. For example,
an AWT button will look like a Windows button
when the program is run on a Windows platform.
The same button will look like a Macintosh
button when the program is run on a Macintosh
platform.
Swing is different from AWT in that Swing components are
100 percent Java, thereby not relying on the native operating
system or platform.
64
Database System Concepts 3.64 ©Silberschatz, Korth and Sudarshan
AWT & Swing
Nowadays, most Java GUI programming is done by using
Swing.
We will discuss the AWT , though, because it is an
important part of GUI programming, and many of the AWT
classes are used in Swing, including the layout managers,
and event-handling classes and interfaces.
The names of the Swing classes all begin with a capital J,
like JButton.
For the most part, an AWT program can be converted to a
Swing program by adding a capital J to the class names
used in the source code and recompiling the code.
12/08/21 65
Database System Concepts 3.65 ©Silberschatz, Korth and Sudarshan
Containers and Components
There are two basic elements of a GUI: containers and
components.
A container is for displaying components,
and components must be displayed within
a container.
A Button is an example of a component,
component
whereas a Frame is an example of a
container.
To display a Button, you place it within a
Frame and display the Frame.
12/08/21 66
Database System Concepts 3.66 ©Silberschatz, Korth and Sudarshan
Swing Components for GUI
The Class Hierarchy depicts that from where Swing components inherit
their common attributes and behavior.
Class Component ( package.java.awt) is subclass of Object that declares
many of the attributes and behaviors common to GUI Component
Object
Component
Container
JComponent
The Swing API uses many of the AWT classes and interfaces.
67
Database System Concepts 3.67 ©Silberschatz, Korth and Sudarshan
Creating Window: using Frame
Every GUI app uses what is called a Frame that comes with
the JDK.
A Frame is a window with borders, a title bar, and buttons
for closing and maximizing or minimizing itself.
It also knows how to resize itself.
Every GUI app subclasses Frame in some way to add more
functionalities to the window frame.
One common task is to tell the system to terminate all
"threads" of the GUI app when the user clicks on the exit
(close) button of the main GUI window.
12/08/21 68
Database System Concepts 3.68 ©Silberschatz, Korth and Sudarshan
Creating Window
12/08/21 69
Database System Concepts 3.69 ©Silberschatz, Korth and Sudarshan
GUI Coordinates
12/08/21 70
Database System Concepts 3.70 ©Silberschatz, Korth and Sudarshan
Using Frame
For example, the point (100,100) is 100 pixels over and 100
pixels down from the upper-left corner of the screen.
Suppose that a Frame is instantiated and given the bounds
(100,100, 300, 400):
Frame f = new Frame();
f.setBounds(100, 100, 300, 400);
The upper-left corner of the Frame is the point (100,100)
relative to the computer screen.
The width of this Frame is 300 and the height is 400, so the
lower-right corner of the Frame is the point (400, 500) of the
computer screen
12/08/21 71
Database System Concepts 3.71 ©Silberschatz, Korth and Sudarshan
GUI Coordinate system
There is another coordinate system of GUI components
referred to as the relative coordinate system.
The relative coordinate system is based on the upper-left
corner of the container that the component is residing in.
The upper-left corner of a container is an origin (0,0), and
components are placed in a container relative to the
container’s origin, not the screen’s origin.
For example, the following statements instantiate a Button,
assign it bounds (20, 200, 60, 40). The Button is then added
to the Frame object instantiated earlier:
Button ok = new Button(“OK”);
ok.setBounds(20, 200, 60, 40);
f.add(ok);
f.add(ok //Add the Button to a Frame
12/08/21 72
Database System Concepts 3.72 ©Silberschatz, Korth and Sudarshan
Coordinates
The upper-left corner of the OK button appears 20 pixels over and
200 pixels down from the upper-left corner of the Frame. The
size of the Button is 60 pixels wide and 40 pixels high.
Assuming that Frame f has not been moved, this puts the Button
120 pixels over and 300 pixels down from the upper-left corner
of the screen. This point changes if the Frame is moved.
However, the relative location of the Button within the Frame
does not move, even if the Frame moves. This is the desired
result of GUI containers and components.
When we move a window, we expect all the components within
the window to move along with it. Therefore, we rarely concern
ourselves with the actual screen coordinates of a component.
The component’s relative coordinates are what are important to
a programmer laying out components in a container.
12/08/21 73
Database System Concepts 3.73 ©Silberschatz, Korth and Sudarshan
java.awt.Frame Class
When working with Frame objects, there are basically
three steps involved to get a Frame window to appear
on the screen:
1. Instantiate the Frame object in memory.
2. Give the Frame object a size using setSize(),
setBounds(), or pack().
3. Make the Frame appear on the screen by invoking
setVisible(true).
12/08/21 74
Database System Concepts 3.74 ©Silberschatz, Korth and Sudarshan
Instantiate the Frame Object
The java.awt.Frame class has four constructors:
12/08/21 75
Database System Concepts 3.75 ©Silberschatz, Korth and Sudarshan
Instantiate Frame Object
Each of the preceding constructors creates a new Frame
object that is initially invisible and has a size of 0 pixels
wide and 0 pixels high.
high
The String passed in to a Frame constructor appears in the
title bar, and the Graphics-Configuration represents where
the image is to be displayed.
If you do not pass in a GraphicsConfiguration object, your
Frame will use the default graphics destination, which in
Windows is the computer screen.
The following statement demonstrates instantiating a new
Frame object in memory:
Frame f = new Frame(“My first window”);
12/08/21 76
Database System Concepts 3.76 ©Silberschatz, Korth and Sudarshan
Windows
This Frame is not displayed on the screen, and it has an initial size
of 0 by 0.
We need to give our Frame a size before displaying it, which can be
done by invoking one of the following five methods:
public void setSize(int width, int height). Sets the size of the Frame
to the given width and height, in pixels.
public void setSize(java.awt.Dimension d). Sets the size of the Frame
to the same width and height as the given Dimension object.
public void setBounds(int x, int y, int width, int height). Sets both the
size and initial location of the window, where x represents the number of
pixels over from the upper-left corner of the screen, and y represents the
number of pixels down from the upper-left corner of the screen.
public void setBounds(java.awt.Rectangle r). Sets the bounds of the
Frame to that of the given Rectangle.
public void pack(). Sets the size of the Frame to be just big enough
to display all its components with their preferred size.
12/08/21 77
Database System Concepts 3.77 ©Silberschatz, Korth and Sudarshan
Create Window
After we have
instantiated a Frame,
given it a size, and
laid out the components within it,
we display the Frame on the screen by
invoking the setVisible() method inherited from the
Component class.
The signature of setVisible() is:
12/08/21 78
Database System Concepts 3.78 ©Silberschatz, Korth and Sudarshan
FrameDemo program
The following FrameDemo program creates a Frame object, sets
its bounds, and displays it on the screen.
Study the program and try to determine its output,
import java.awt.*;
public class FrameDemo
{
public static void main(String [] args)
{
Frame f = new Frame(“My first window”);
f.setBounds(100,100, 400, 300);
f.setVisible(true);
}
}
12/08/21 79
Database System Concepts 3.79 ©Silberschatz, Korth and Sudarshan
Window
12/08/21 80
Database System Concepts 3.80 ©Silberschatz, Korth and Sudarshan
Creating Window with Swing
Let’s look at the steps involved in creating a JFrame. You start
by instantiating a JFrame using one of the following constructors:
public JFrame(). Creates a new JFrame with no message in
the title bar.
public JFrame(String title). Creates a new JFrame with the
given String appearing in the title bar.
public JFrame(GraphicsConfiguration gc). Creates a JFrame
with the specified GraphicsConfiguration of a screen device.
public JFrame(String title, GraphicsConfiguration gc).
Creates a Jframe with the specified title and
GraphicsConfiguration.
81
Database System Concepts 3.81 ©Silberschatz, Korth and Sudarshan
The constructors are similar to those in the Frame class, and the
parameters have the same uses. The following statement
instantiates a JFrame with “My first JFrame” in the title bar:
JFrame f = new JFrame(“My first JFrame”);
As with Frame objects, this JFrame is initially not visible and has
a size of 0 pixels by 0 pixels.
You invoke one of the setSize(), setBounds(), or pack() methods
to give the JFrame a size and then invoke setVisible() to make it
visible.
12/08/21 82
Database System Concepts 3.82 ©Silberschatz, Korth and Sudarshan
The following JFrameDemo program demonstrates creating and
displaying a JFrame object.
import javax.swing.*;
public class JFrameDemo
{
public static void main(String [] args)
{
JFrame f = new JFrame(“My first JFrame”);
f.setSize(400, 300);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
12/08/21 83
Database System Concepts 3.83 ©Silberschatz, Korth and Sudarshan
Using Swing
Clicking the X in the title bar of a JFrame causes the window to be hidden
by default, but this does not cause your program to stop executing.
We
need to press Ctrl+c at the command prompt to stop the JVM, even though
our JFrame is no longer visible on the screen.
12/08/21 84
Database System Concepts 3.84 ©Silberschatz, Korth and Sudarshan
12/08/21 85
Database System Concepts 3.85 ©Silberschatz, Korth and Sudarshan
Java : OOM Characteristics & Implementations
Inheritance, Polymorphism & Abstraction
Interface: Java Implementation & Applications
Java API and Applets
User Defined Interfaces
Design Principles:
Principles GoF & Liskov’s Principles
86
Database System Concepts 3.86 ©Silberschatz, Korth and Sudarshan
GUI, Event Handling & Applet
An applet is a Java program that runs in a Web
browser.
An applet can be a fully functional Java
application because it has the entire Java API at
its disposal.
Writing an applet is similar to creating a graphical
user interface (GUI) program, because an applet is
a Container object.
Containers, Components, Layout managers, and
event handling are a big part of developing
applets.
12/08/21 87
Database System Concepts 3.87 ©Silberschatz, Korth and Sudarshan
Containers and Components
There are two basic elements of a GUI: containers and
components.
A container is for displaying components,
and components must be displayed within a
container.
A Button is an example of a component,
whereas a Frame is an example of a
container.
To display a Button, you place it within a
Frame and display the Frame.
12/08/21 88
Database System Concepts 3.88 ©Silberschatz, Korth and Sudarshan
Swing Components for GUI
The Class Hierarchy depicts that from where Swing components inherit
their common attributes and behavior.
Class Component ( package.java.awt) is subclass of Object that declares
many of the attributes and behaviors common to GUI Component
Object
Component
Container
JComponent
The Swing API uses many of the AWT classes and interfaces.
89
Database System Concepts 3.89 ©Silberschatz, Korth and Sudarshan
GUI
Component is an abstract class that is the
parent class of the various GUI components of
the AWT: Button, Checkbox, Choice, Label,
List, and Text- Component.
Container is an abstract class that is the
parent class of the containers of the AWT:
Window, Panel, and ScrollPane.
Child objects of Component are placed within
child objects of Container.
For example, a Button can be placed within a
Panel, or a List can be placed within a Frame.
Frame
12/08/21 90
Database System Concepts 3.90 ©Silberschatz, Korth and Sudarshan
Event handling
Normally a user interacts with an application’s GUI to indicate the tasks
that the application should perform.
When you write an e-mail in the email software, clicking the Send button
tells the application to send the email to the specified email addresses.
When the user interacts with a GUI component the interaction- known as
an event - drives the program to perform a task.
Some common events (user-interactions) that might cause an
application to perform a task include;
clicking a button,
typing in a text field,
selecting an item from a menu,
menu
closing a window
moving the mouse.
The code that performs a task in response to an event is called an event
handler and the overall process of responding to events is known as
event handling.
91
Database System Concepts 3.91 ©Silberschatz, Korth and Sudarshan
Event Handling & GUI
GUI programs having only Menus using Frame Class do
not have any functionality beyond looking good.
We are required to understand how to create GUI
components and how to handle their events.
Now we will discuss the delegation model, the architecture
behind event handling in Java.
We will then look at the various components of the AWT and
Swing APIs, discussing how to create them and how to
handle their events.
Java GUI programming uses the Delegation Model for
handling the events of components and containers.
The source of an event invokes a method on a registered
listener of the event, with the two objects communicating via
a common interface.
92
Database System Concepts 3.92 ©Silberschatz, Korth and Sudarshan
The Delegation Model
Events in Java are fired and handled using a design known as the
delegation model.
With the delegation model, a source generates an event and a listener
handles it, creating an object-oriented approach to handling events. (A
class is written to handle the events of a component.)
There are 03 players in delegation model:-
12/08/21 93
Database System Concepts 3.93 ©Silberschatz, Korth and Sudarshan
Delegation Model
The Delegation model delegates an event’s processing to
the Event listener.
Many different type of events can occur when the user
interacts with a GUI.
The information about any GUI event that occurs is
stored in an object of a class that extends AWTEvent
Figure on next page illustrates a hierarchy containing
many event classes from the package java.awt.event.
These event types are used with both AWT Swing
components.
12/08/21 94
Database System Concepts 3.94 ©Silberschatz, Korth and Sudarshan
Some Event classes of package java.awt.event
12/08/21 95
Database System Concepts 3.95 ©Silberschatz, Korth and Sudarshan
Event handling
For example, when a user clicks a java.awt.Button,
Button the
Button generates a java.awt.event.ActionEvent.
ActionEvent
The Button invokes the actionPerformed() method on each
registered listener of the Button, passing in the
ActionEvent object.
object
The actionPerformed() method is defined in the
java.awt.event.ActionListener interface, which each
listener must implement.
In this scenario, the Button is the source of the event, the
interface is ActionListener, and the listener is any class
that implements ActionListener and registers itself with
the Button.
12/08/21 96
Database System Concepts 3.96 ©Silberschatz, Korth and Sudarshan
Events handling : Ques.
Q: How do you register a listener with a Button?
A: Two steps are involved. You first need to write a class that
implements ActionListener. You then invoke the addActionListener()
method on the Button, passing in an instance of your class.
Q: So do all components generate an ActionEvent?
A: No. There are many types of events, and each event has a
corresponding listener interface. For example, windows generate
WindowEvent objects and invoke a method from the WindowListener
interface. A check box generates an ItemEvent and invokes a
method in the ItemListener interface.
12/08/21 98
Database System Concepts 3.98 ©Silberschatz, Korth and Sudarshan
Event Listener
The event listener interface contains the methods that the
event source invokes on the listener,
And it provides the means of communication between the
source of the event and the listener of the event.
Each type of event has a corresponding listener interface.
An event listener interface extends the
java.util.EventListener interface.
The EventListener interface does not contain any methods,
but is used for tagging an event listener interface for use
with the delegation model of event handling.
12/08/21 99
Database System Concepts 3.99 ©Silberschatz, Korth and Sudarshan
Event listener interface
For example, the ActionListener interface is defined as:
package java.awt.event;
public interface ActionListener extends java.util.EventListener
{
public void actionPerformed(ActionEvent e);
}
Notice that ActionListener extends EventListener and is in the
java.awt.event package, which is where all the AWT event classes
and listener interfaces are defined.
The javax.swing.event package contains the event classes and
listener interfaces unique to Swing.
The AWT components only generate AWT events, while Swing
components generate both AWT and Swing events.
12/08/21 100
Database System Concepts 3.100 ©Silberschatz, Korth and Sudarshan
12/08/21 101
Database System Concepts 3.101 ©Silberschatz, Korth and Sudarshan
Applets
An applet is a special kind of Java program that a browser
enabled with Java technology can download from the internet
and run.
An applet is typically embedded inside a web page and runs
in the context of a browser.
An applet must be a subclass of the java.applet.Applet class.
The Applet class provides the standard interface between the
applet and the browser environment.
Swing provides a special subclass of the Applet class called
javax.swing.JApplet.
The JApplet class should be used for all applets that use
Swing components to construct their graphical user
interfaces (GUIs).
102
Database System Concepts 3.102 ©Silberschatz, Korth and Sudarshan
Applets
There are some important differences between an applet and a
standalone Java application, including the following:
An applet is a Java class that extends the java.applet.Applet
class.
A main() method is not invoked on an applet, and an applet class
will (typically) not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the
code for the applet is downloaded to the user’s machine.
A user must have a JVM on his or her machine. The JVM can be
either a plug-in of the Web browser or a separate runtime
environment.
The JVM on the user’s machine creates an instance of the applet
class and invokes various methods during the applet’s lifetime.
103
Database System Concepts 3.103 ©Silberschatz, Korth and Sudarshan
Truly Platform independent
Applets have strict security rules that are enforced by the Web
browser. The security of an applet is often referred to as sandbox
security, comparing the applet to a child playing in a sandbox with
various rules that must be followed.
Other classes that the applet needs can be downloaded in a single
Java Archive (JAR) file.
Because applets are a part of a Web page, however, they can be
accessed by any Web browser using any operating system on any
device, and therefore can be executed on many different platforms
and devices.
I can run an applet using Windows XP and Internet Explorer, and you
can run the same applet on a Macintosh running Netscape Navigator.
We will see how to write an applet and embed it in an HTMLpage.
This will involve writing some HTML, so basics will be reqd.
JAR files will also be discussed in detail because they are important
aspects of applets.
12/08/21 104
Database System Concepts 3.104 ©Silberschatz, Korth and Sudarshan
The java.applet.Applet Class
12/08/21 105
Database System Concepts 3.105 ©Silberschatz, Korth and Sudarshan
Panel Container for Applet
The Class Hierarchy depicts that Panel inherit
their common attributes and behavior .
Class Panel ( package.java.awt) is subclass of Container and Applet is
subclass of Panel
Object
Component
Container
Panel
Applet 106
Database System Concepts 3.106 ©Silberschatz, Korth and Sudarshan
Writing Applet
An Applet Class extends Panel means that an applet is
a panel,
panel which is a java.awt.Container;
therefore, an applet can have components added
to it just like any container,
as well as have a Layout manager assigned to it,
and you can even nest panels within an applet to
create the GUI you want.
The default layout manager for a panel is the FlowLayout layout
manager.
Let’s take a look at a simple Applet class named
HelloWorldApplet which extends java.applet.Applet.
12/08/21 107
Database System Concepts 3.107 ©Silberschatz, Korth and Sudarshan
HTML embedding Applet
Three attributes of the <applet> tag that are required:
12/08/21 108
Database System Concepts 3.108 ©Silberschatz, Korth and Sudarshan
Applet embedding
An applet can actually be embedded within any other application,
not just a Web browser.
If your applet is going to be embedded in a Web page, it must
extend the Applet class.
If your applet is going to be embedded in some other application,
extending Applet is not required.
On the same line, we may develop Swing Applets using JApplet.
JApplet class is subclass of Applet so it inherites all the methods
of Applet.
The purpose of the JApplet class is to provide support for Swing.
Probably the biggest difference between an Applet and a JApplet
is how components are added to them.
A JApplet has three panes, much like a JFrame, and components
are added to the content pane of the Japplet.
109
Database System Concepts 3.109 ©Silberschatz, Korth and Sudarshan
Life Cycle methods of an Applet
Let us discuss the five applet methods that are called
by the applet container from the time the applet is
loaded into the browser to the time that it is terminated
by the browser.
These methods correspond to various aspects of an
applet’s life cycle.
These methods are inherited from class Japplet. that
the browser invokes these methods on your applet.
1) public void init().
2) public void start().
3) public void stop().
4) public void destroy().
5) public void paint(Graphics g).
12/08/21 110
Database System Concepts 3.110 ©Silberschatz, Korth and Sudarshan
HelloWorldApplet Class
Few comments about this applet:
This Class is Container & adds a button .
There is no main() & Most of the code of the HelloWorldApplet
class appears in the init() method, which is overriding the init()
method from the parent class Applet.
The Web browser invokes init() immediately after it creates an
instance of HelloWorldApplet Class.
We could have used a constructor, but we wanted to
demonstrate the init() method.
Within init(), the layout of the applet is changed to BorderLayout. (It
had FlowLayout by default.)
The event handling is done in the ensuing PrintHello class. Study the
following code, and try to determine what this applet does.
A PrintHello object is listening for an ActionEvent from the Go button.
111
Database System Concepts 3.111 ©Silberschatz, Korth and Sudarshan
import java.applet.*; import java.awt.*;
import java.awt.*; import java.awt.event.*;
public class HelloWorldApplet extends Applet public class PrintHello implements
{ ActionListener
private Button go; {
private TextField name; private Label label;
private Label hello; private TextField textField;
public void init()
public PrintHello(Label s, TextField t
{
{
label = s;
go = new Button(“Go”);
textField = t;
name = new TextField();
}
hello = new Label(“”, Label.CENTER);
public void
this.setLayout(new BorderLayout()); actionPerformed(ActionEvent a)
this.add(name, BorderLayout.NORTH); {
Panel center = new Panel(); String name = textField.getText();
center.add(go); if(name != null && !(name.equals(“”)
this.add(center, BorderLayout.CENTER); {
this.add(hello, BorderLayout.SOUTH); label.setText(“Hello, “ + name);
//Set up the event handling. }
PrintHello listener = new PrintHello(hello, name); }
go.addActionListener(listener); }
} 112
}
Database System Concepts 3.112 ©Silberschatz, Korth and Sudarshan
Applet
When a user views an HTML page that contains an
applet, the code for the applet is downloaded to
the user’s machine.
A user must have a JVM on his or her machine.
The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
The JVM on the user’s machine creates an
instance of the applet class and invokes various
methods during the applet’s lifetime.
12/08/21 113
Database System Concepts 3.113 ©Silberschatz, Korth and Sudarshan
Applet
This applet is displayed in a Web page named hello.html using
the <applet> tag.
The HTML looks similar to:
<html>
<body>
<h2>Enter your name and click the button.</h2>
<applet code=”HelloWorldApplet”
HelloWorldApplet
width=”200”
height=”75”>
</applet>
</body>
</html>
12/08/21 114
Database System Concepts 3.114 ©Silberschatz, Korth and Sudarshan
Sample view of HelloWorldApplet in hello.html file
Sample
12/08/21 115
Database System Concepts 3.115 ©Silberschatz, Korth and Sudarshan
Applet embedding
An applet can actually be embedded within any other
application, not just a Web browser.
If your applet is going to be embedded in a Web page, it must
extend the Applet class. If your applet is going to be embedded
in some other application, extending Applet is not required.
On the same line, we may develop Swing Applets using
JApplet.
JApplet class is subclass of Applet so it inherites all the methods of
Applet.
The purpose of the JApplet class is to provide support for Swing.
Probably the biggest difference between an applet and a
JApplet is how components are added to them.
A JApplet has three panes, much like a JFrame, and
components are added to the content pane of the Japplet.
116
Database System Concepts 3.116 ©Silberschatz, Korth and Sudarshan
Life Cycle methods of an Applet
Let us discuss the five applet methods that are called
by the applet container from the time the applet is
loaded into the browser to the time that it is terminated
by the browser.
These methods correspond to various aspects of an
applet’s life cycle.
These methods are inherited from class Japplet. that
the browser invokes these methods on your applet.
1) public void init().
2) public void start().
3) public void stop().
4) public void destroy().
5) public void paint(Graphics g).
12/08/21 117
Database System Concepts 3.117 ©Silberschatz, Korth and Sudarshan
1) public void init(). The first method invoked on the applet when it is
initially instantiated. This is your chance to perform any initialization,
such as locating resources or preparing event handlers.
2) public void start(). Invoked by the browser to inform the applet
that it should start executing. The start() method is called right after the
init() method, and is also called when the page is revisited. This is a
good time to start any threads or other tasks like displaying animation
or playing sound.
3) public void stop(). Invoked by the Web browser to inform the
applet that it should stop executing. The stop() method is called right
before the destroy() method is invoked, and also when a user leaves
the Web page.Typically, anything you started in the start() method is
stopped in the stop() method.
4) public void destroy(). Invoked by the Web browser to inform the
applet that it is about to be destroyed (in other words, garbage
collected). Typically,any resources allocated in the init() method are
freed in the destroy() method.
5) public void paint(Graphics g). Invoked immediately after the start()
method, and also any time the applet needs to repaint itself in the
118
Database System Concepts 3.118 ©Silberschatz, Korth and Sudarshan
When a user views a Web page that contains an applet, the following
sequence of events occurs regarding the life cycle of the applet:
1. The Web browser downloads the necessary bytecode and JAR file from
the Web server where the code is located. (This Web server is referred to
as the code base.)
2. The browser creates an instance of the Applet class, invoking the default
constructor.
3. The applet is displayed in the Web page, with the location and size of the
applet determined by the HTML.
4. The browser invokes the init() method on the applet.
5. The browser invokes the start() method on the applet.
6. The browser invokes the paint() method on the applet.
7. The applet is now live and running within the Web page.
8. The browser calls paint() whenever the applet needs to repaint itself.
9. The browser invokes the stop() method when the user leaves the Web
page or the applet is about to be destroyed.
10. The browser invokes the destroy() method just before destroying the
applet.
119
Database System Concepts 3.119 ©Silberschatz, Korth and Sudarshan
Applet & HTML
If a Web browser does not understand the <applet> tag, it will ignore
the tag and display any HTML that appears within the opening and
closing <applet> tags.
For example, the following HTML displays a message that the user is
unable to see the applet that was intended to appear:
<applet code=”com.world.MyApplet”
width=”200”
height=”348”
alt=”MyApplet failed”>
failed
<h2>Your browser does not support applets!</h2>
<p>To view this page correctly, you will need to find a Web
browser that provides support for applets, or install the
Java Plug-in.</p>
</applet>
12/08/21 120
Database System Concepts 3.120 ©Silberschatz, Korth and Sudarshan
Applet & HTML
Visitors to this page who have a Web browser that supports
applets will not see the message about their browser not
supporting applets. Note that if their browser supports
applets but, for some reason, cannot run applets, the visitor
will see the alt message “MyApplet failed.”
12/08/21 121
Database System Concepts 3.121 ©Silberschatz, Korth and Sudarshan
OO Design Principles
Design Principles
GoF & Design Patterns: Overview
OO Design Principles
Open Closed Principle
Dependency Inversion Principle
Interface Segregation Principle
Single Responsibility Principle
Liskov's Substitution Principle
Analyze OOPS characteristics and don’t overuse
Inheritance, Encapsulation & Polymorphism
Inheritance Vs Composition
12/08/21 122
Database System Concepts 3.122 ©Silberschatz, Korth and Sudarshan
Design Principles
What are Software Design Principles?
Software design principles represent a set of guidelines that helps us to
avoid having a bad design.
The design principles are associated to Robert Martin who gathered them
in "Agile Software Development: Principles, Patterns, and Practices".
According to Robert Martin there are 3 important characteristics of a bad
design that should be avoided:
Rigidity - It is hard to change because every change affects too many other
parts of the system.
Fragility - When you make a change, unexpected parts of the system
break.
Immobility - It is hard to reuse in another application because it cannot be
disentangled from the current application.
Barabara Liskov got Turing Award for her research in OO design
principles.(2008)
124
Database System Concepts 3.124 ©Silberschatz, Korth and Sudarshan
Design Patterns
Patterns originated as an architectural concept by Christopher
Alexander (1977/79). In 1987, Kent Beck and Ward
Cunningham began experimenting with the idea of applying
patterns to programming and presented their results at the
OOPSLA conference that year.
In the following years, Beck, Cunningham and others followed
up on this work.
Design patterns gained popularity after the book Design
Patterns: Elements of Reusable Object-Oriented Software was
published in 1994 by the so-called "Gang of Four" (Gamma et
al)
In 2009 over 30 contributors collaborated with Thomas Erl on
his book, SOA Design Patterns.
The goal of this book was to establish a de facto catalog of
design patterns for SOA and service-orientation. (Over 200+ IT
professionals participated world-wide in reviewing Erl's book
and patterns.) These patterns are also published and
125
discussed on the community research site soapatterns.org
Database System Concepts 3.125 ©Silberschatz, Korth and Sudarshan
Design Patterns: Elements of Reusable Object-
Oriented Software
126
Database System Concepts 3.126 ©Silberschatz, Korth and Sudarshan
Design Patterns
GoF proposed some significant concepts;
concepts
"Program to an 'interface', not an 'implementation'." (Gang of Four
1995:18)
"Favor 'object composition' over 'class inheritance'." (Gang of Four
1995:20)
Case study on "the design of a 'What-You-See-Is-What-You-Get' (or
'WYSIWYG') document editor called Lexi.
seven problems that must be addressed in order to properly design Lexi.
Each problem is analyzed in-depth, and solutions are proposed. Each
solution is explained in full, including pseudo-code and Unified Modeling
Language where appropriate.
Each solution is associated directly with one or more design patterns. It
is shown how the solution is a direct implementation of that design
pattern.
Design patterns were originally grouped into the categories: creational
patterns, structural patterns, and behavioral patterns, and described
using the concepts of delegation, aggregation, and consultation.
127
Database System Concepts 3.127 ©Silberschatz, Korth and Sudarshan
Design Principles
Implementations
128
Database System Concepts 3.128 ©Silberschatz, Korth and Sudarshan
Open Closed Principle
129
Database System Concepts 3.129 ©Silberschatz, Korth and Sudarshan
Open Closed Principle
The Open Closed Principle (OCP) is undoubtedly the most
important of all the class category principles. In fact, each of
the remaining class principles are derived from OCP.
It originated from the work of Bertrand Meyer, who is
recognized as an authority on the object-oriented paradigm.
When referring to the classes Open Closed Principle can be
ensured by use of Abstract Classes and concrete classes
for implementing their behavior.
Some ways to do this include Polymorphism/Inheritance,
Composition, Inversion of Control, Aspect-Oriented
Programming, and many other principles, patterns, and
techniques of OOAD.
It is not possible to have all the modules of a software
system satisfy the OCP, but we should attempt to minimize
the number of modules that do not satisfy it
130
Database System Concepts 3.130 ©Silberschatz, Korth and Sudarshan
Interface Segregation Principle
Clients should not be forced to depend upon interfaces that
they don't use.
This principle teaches us to take care how we write our
interfaces.
When we write our interfaces we should take care to add only
methods that should be there.
If we add methods that should not be there the classes
implementing the interface will have to implement those
methods as well.
For example if we create an interface called Worker and add a
method lunch break, all the workers will have to implement it.
What if the worker is a robot?
Interfaces containing methods that are not specific to it are
called polluted or fat interfaces. We should avoid them.
131
Database System Concepts 3.131 ©Silberschatz, Korth and Sudarshan
Interfaces
An interface is the set of methods one object
knows it can invoke on another object
An object can have many interfaces.
(Essentially, an interface is a subset of all the
methods that an object implements).
A type is a specific interface of an object
Different objects can have the same type and
the same object can have many different types
An object is known by other objects only
through its interface
Interfaces are the key to pluggability!
135
Database System Concepts 3.135 ©Silberschatz, Korth and Sudarshan
The Liskov Substitution Principle
Motivation
All the time we design a program module and we create some class
hierarchies. Then we extend some classes creating some derived
classes.
We must make sure that the new derived classes just extend
without replacing the functionality of old classes. Otherwise the new
classes can produce undesired effects when they are used in
existing program modules.
Likov's Substitution Principle states that if a program module is
using a Base class, then the reference to the Base class can be
replaced with a Derived class without affecting the functionality of
the program module.
Intent
Derived types must be completely substitutable for their base
types.
140
Database System Concepts 3.140 ©Silberschatz, Korth and Sudarshan
LSP Example
Consider the following Rectangle class:
Observations:
// A Square class.
public class Square extends Rectangle {
public Square(double s)
{super(s, s);
}
public void setWidth(double w) {
super.setWidth(w);
super.setHeight(w);
}
public void setHeight(double h) {
super.setHeight(h);
super.setWidth(h);
}
}
148
Database System Concepts 3.148 ©Silberschatz, Korth and Sudarshan
OOSE Design Principles
OOM characteristics & implementation
Inheritance vs Composition
Advantages & Disadvantages
149
Database System Concepts 3.149 ©Silberschatz, Korth and Sudarshan
Types of Inheritance & Polymorphic behavior
A A B
A
B D
B C C
B
Hierarchical Multiple
C Inheritance Inheritance
Single
Inheritance Multi Level
Inheritance
150
Database System Concepts 3.150 ©Silberschatz, Korth and Sudarshan
Multiple inheritance …
References can be explored in multiple inheritance, Ex.:
When we apply the reference variable facts to a Deer object reference, the
following declarations are legal:
Deer d = new Deer();
Animal a = d;
Vegetarian v = d; Object o = d;
All the reference variables d,a,v,o refer to the same Deer object in the heap.
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
float 32 bits
double 64 bits
char 16 bits
Boolean
152
Database System Concepts 3.152 ©Silberschatz, Korth and Sudarshan
Polymorphic behavior
Polymorphism with other OOP characteristics
create many interesting situations and change the
behavior of Objects.
Polymorphism manifests itself in Java in the form of
multiple methods having the same name.
In some cases, multiple methods have the same
name, but different formal argument lists (overloaded
methods).
In other cases, multiple methods have the same
name, same return type, and same formal argument
list (overridden methods).
153
Database System Concepts 3.153 ©Silberschatz, Korth and Sudarshan
Compile-time polymorphism
Some authors refer to method overloading as a form of
compile-time polymorphism, as distinguished from run-time
polymorphism.
This distinction comes from the fact that, for each method
invocation, the compiler determines which method (from a
group of overloaded methods) will be executed, and this
decision is made when the program is compiled. (In
contrast, to that the determination of which overridden
method to execute isn't made until runtime.)
Some of the interesting concepts associated with
polymorphism are Heterogeneous Collections, Polymorphic
parameters, Abstraction and Virtual methods.
154
Database System Concepts 3.154 ©Silberschatz, Korth and Sudarshan
Virtual Methods
155
Database System Concepts 3.155 ©Silberschatz, Korth and Sudarshan
Virtual Methods
The concept of the virtual function addresses the following problem:
In OOP when a derived class inherits from a parent class, an object
of the child class may be referred to (or cast) as either being the
parent class type or the child class type.
If there are parent class functions overridden by the child class, a
problem then arises when a child object has been cast as the parent
class type.
When a child object is referred to as being of the parent's type, the
desired function call behavior is ambiguous.
The distinction between virtual and not virtual resolves this
ambiguity. If the function in question is designated "virtual" in the
parent class then the child class's function would be called (if it
exists). If it is not virtual, the parent class's function would be called.
Virtual functions overcome the problems with the type-field solution
by allowing the programmer to declare functions in a parent class
that can be redefined in each child class.
156
Database System Concepts 3.156 ©Silberschatz, Korth and Sudarshan
Virtual Method
In C++, virtual methods are not the default behavior of methods. In
fact, you must use the C++ keyword virtual to “turn on” the
behavior of virtual method invocation.
The opposite is true in Java. All methods in Java are virtual by
default (virtual is not a keyword in Java),
Java In Java the methods can
be overridden at run-time.
What to do so as to make an method in Java to be non-virtual
method ?
The only way to avoid this behavior of virtual methods is to declare
a method final.
Final methods cannot be overridden, so the JVM does not need to
worry about looking down the inheritance hierarchy and trying to
determine if a child has overridden the method.
For this reasons, final methods have a performance benefit
because the overhead of virtual method invocation is avoided.
We should only declare a method as final if it is truly part of the
design of your class.
157
Database System Concepts 3.157 ©Silberschatz, Korth and Sudarshan
The final Keyword
The final keyword is used for creating constant variables. A
final variable cannot be changed after it has been assigned
a value.
Now that we have seen inheritance and method overriding,
the other two uses of the final keyword can be :
Final class. A class can be declared final. A final class
cannot be subclassed.
Final method. A method can be declared final. A final
method cannot be overridden.
Several of the classes in the Java API are declared final. For
example, the String class is final, so you cannot write a
class that extends String.
158
Database System Concepts 3.158 ©Silberschatz, Korth and Sudarshan
Final
The final keyword appears before the class keyword when
declaring a final class. For example:
public final class Hourly extends Employee
{
//Class definition...
}
A compiler error is generated if you try to write a class that
subclasses Hourly. The following class declaration will not compile:
public class PartTime extends Hourly //error!
{
//Class definition...
}
159
Database System Concepts 3.159 ©Silberschatz, Korth and Sudarshan
final Methods
When a child class overrides a method in the parent class,
the overridden method is essentially hidden.
The only way the parent method can be invoked is if the
child method explicitly invokes it. If you write a method with
important behavior that you do not want a child class to
override, you can declare the method final.
A final method cannot be overridden by a child class.
If the implementations of some methods are essential for
the proper behavior of an object, and these methods cannot
be overridden by any class.
160
Database System Concepts 3.160 ©Silberschatz, Korth and Sudarshan
The Wrapper Classes
There are situations in Java programming where you want a primitive data
type to take on the form of java.lang.Object.
The developers of Java realized this and created what is referred to as the
wrapper classes.
There are eight wrapper classes, one for each of the eight primitive data
types. We use the term wrapper because their main purpose is to wrap a
primitive data type into a Java object.
For example, the java.lang.Integer class is used to wrap an int. The Integer
class has two constructors:
public Integer(int value)
public Integer(String value) throws NumberFormatException
(Note that the String parameter is parsed into an int.) Whichever constructor
you use, the
int value is stored as a field in the class and is retrieved using the method:
public int intValue()
12/08/21 161
Database System Concepts 3.161 ©Silberschatz, Korth and Sudarshan
Wrapper Class
Why create an object to store a simple 32-bit int?
Because the wrapper class Integer is just that—a class. It
therefore extends Object, and can be used in any situation
where an Object is required.
Wrapper classes are commonly used with the Java Collections
Framework, a set of classes that represent commonly used data
structures such as sets, trees , and hash tables.
Each wrapper class has constructors similar to the two in
Integer, and each class has methods for retrieving the primitive
type from the wrapper object.
View the J2SE documentation to view the constructors and
methods of each class.
12/08/21 162
Database System Concepts 3.162 ©Silberschatz, Korth and Sudarshan
Abstraction
Abstraction refers to the ability to make a class abstract
in OOP.
An abstract class is one that cannot be instantiated.
All other functionality of the class still exists, and its
fields, methods, and constructors are all accessed in
the same manner.
You just cannot create an instance of the class.
An abstract class might initially seem like an odd
design.
Why write a class and not allow anyone to create
instances of it?
In most situations, the design of the class is such that
no one would want an instance of the class.
163
Database System Concepts 3.163 ©Silberschatz, Korth and Sudarshan
The instanceof Keyword
Sometimes knowing the type of an object during run time is
useful.
The instanceof keyword is used to determine if an object is
an instance of a particular class.
The instanceof operator has the general form:
164
Database System Concepts 3.164 ©Silberschatz, Korth and Sudarshan
Instanceof keyword
The following valid statements instantiate an Hourly object,
referring to it with an Employee reference. The reference is cast to
Hourly to invoke the methods of the Hourly class.
Employee h = new Hourly(“Abe Lincoln”, “Springfield, IL”, 16,
8.00);
((Hourly) h).setHoursWorked(40);
((Hourly) h).computePay();
h.mailCheck();
Because h is of type Employee, h can refer to an Employee
object, a Salary object, or an Hourly object. The instanceof
keyword can determine the data type of a reference, syntax is
as follows:
reference instanceof ClassName
165
Database System Concepts 3.165 ©Silberschatz, Korth and Sudarshan
Instanceof …
As we know the instanceof operator returns true if the
reference is of the given class type, and false otherwise. For
example, before casting h to a Salary object, we should
have made the following check:
if(h instanceof Salary)
{
Salary s = (Salary) h;
s.computePay(); //And so on
}
The cast above occurs only when h actually refers to a
Salary object,
166
Database System Concepts 3.166 ©Silberschatz, Korth and Sudarshan
Polymorphic Parameters
Now that we have discussed parent class references and known
the instanceof keyword,
We can see the benefit of polymorphism known as polymorphic
parameters.
When a method has a parameter that is a reference, any object
that is compatible with that reference can be passed in, allowing
a method to accept parameters of different data types.
For example, suppose that a method has an Employee
parameter:
public void payEmployee(Employee e)
An Employee object needs to be passed in to the payEmployee()
method. If Salary and Hourly extend Employee, a Salary or
Hourly object could also be passed in to payEmployee() because
through polymorphism a Salary or Hourly object is also an
Employee object.
167
Database System Concepts 3.167 ©Silberschatz, Korth and Sudarshan
Polymorphic params
168
Database System Concepts 3.168 ©Silberschatz, Korth and Sudarshan
The Boss class contains a payEmployee() method with an
Employee parameter. The method casts the parameter to its
appropriate data type & invokes computePay().
public class Boss
{
public void payEmployee(Employee e) The payEmployee() method in the
{ Boss class cannot simply invoke
double pay = 0.0;
computePay()
on the parameter e because the
if(e instanceof Salary)
parameter is an Employee type, and
{
the Employee class does not contain
pay = ((Salary) e).computePay(); a computePay() method. To invoke
} computePay(),
else if(e instanceof Hourly) the reference e must be cast to its
{ appropriate data type, which is
pay = (((Hourly) e).computePay(); determined by using the instanceof
} keyword.
System.out.println(“Pay = “ + pay);
Notice that the mailCheck()
method can be invoked without
e.mailCheck();
casting because mailCheck() is in the
}
Employee class and e is an Employee
} reference.
169
Database System Concepts 3.169 ©Silberschatz, Korth and Sudarshan
The payEmployee() method can be invoked passing in any
Employee object.
If a new Contractor class is written that extends Employee,
Contractor objects can be passed into the existing
payEmployee() method without changing the method’s
signature.
Unfortunately, we would have to modify the body of
payEmployee() and add an instanceof check for Contractor,
which is not good design
170
Database System Concepts 3.170 ©Silberschatz, Korth and Sudarshan
Virtual Methods
In object-oriented programming, a virtual function
or virtual method is a function or method whose
behavior can be overridden within an inheriting
class by a function with the same signature.
171
Database System Concepts 3.171 ©Silberschatz, Korth and Sudarshan
Virtual Methods
The concept of the virtual function solves the following problem:
In OOP when a derived class inherits from a base class, an object
of the derived class may be referred to (or cast) as either being the
base class type or the derived class type. If there are base class
functions overridden by the derived class, a problem then arises
when a derived object has been cast as the base class type.
When a derived object is referred to as being of the base's type,
the desired function call behavior is ambiguous.
The distinction between virtual and not virtual resolves this
ambiguity. If the function in question is designated "virtual" in the
base class then the derived class's function would be called (if it
exists). If it is not virtual, the base class's function would be called.
Virtual functions overcome the problems with the type-field solution
by allowing the programmer to declare functions in a base class
that can be redefined in each derived class.
172
Database System Concepts 3.172 ©Silberschatz, Korth and Sudarshan