Está en la página 1de 172

OOM 03

By

Prof. Dr. O. P. Vyas


M.Tech.(CS), Ph.D. ( I.I.T. Kharagpur )
DAAD Fellow ( Germany )
AOTS Fellow ( Japan)
Java : OOM Characteristics & Implementations
 Polymorphism, Abstraction & Interface
Java Implementation
 Project with Java: GUI & Applets
 Design Principles: GoF & Design Patterns
 Using AWT & Swing
 Event Handling in Java : Delegation model
 Event Source , Listener & Interface
 Applets & Standalone applications
 Writing Applet
 Embedding in HTML
12/08/21
 Life 2
Cycle of Applet
Database System Concepts 3.2 ©Silberschatz, Korth and Sudarshan
Three principles of OOM

 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

 Two important effects that stem from


inheritance are polymorphism—where draw()
an object can take on many forms—and draw()
abstraction.

Database System Concepts 3.3 ©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).

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

 Polymorphism is the capability of an action


or method to do different things based on the
object that it is acting upon. Overloading and
overriding are two types of polymorphism .
 We say a method is polymorphic if the action
performed by the method depends on the
actual type of the object to which the method
is applied.
 Generally, it allows us to mix methods and
objects of different types in a consistent way.

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

Database System Concepts 3.9 ©Silberschatz, Korth and Sudarshan


Polymorphism for Simulation program
 We design a program which maintains the array of
references to objects of the various Animal subclass.
 To simulate the animal’s movements, the program sends
each object the same message once per second move().
 However each specific type of Animal responds to a move
message in a unique way:
A Fish swim three feet,
 A Bird might fly ten feet
 A Person may walk five feet.
 Each Object know how to modify its x-y coordinates
appropriately for its specific types of movements.
 Capability of each object to “do the right thing” in response
to the same method call is resulting in to a variety of objects
having “many forms” of results thus termed as
10
Polymorphism
Database System Concepts 3.10 ©Silberschatz, Korth and Sudarshan
Polymorphic behaviour
 Following statements are used to implement Polymorphic
behaviour of various Objects

Animal [] A = new Animal[3];


A[0] = new Bird();
A[1] = new Person();
A[2] = new Fish();
for (int i = 0; i < A.length; i++)
A[i].move();

• References are all the same, but objects are not


• Method invoked is that associated with the OBJECT, NOT
with the reference

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

 Project with Java: GUI & Applets


 Using AWT & Swing
 Event Handling in Java : Delegation model
 Event Source , Listener & Interface

 Applets & Standalone applications: Writing Applet


 Embedding in HTML

 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.

car Super class


 A well designed hierarchy of
classes is the basis for re auto-
manual Subclasses
using the code in which lot of matic
time and expertise was
invested in developing &
draw() draw()
testing.

Database System Concepts 3.13 ©Silberschatz, Korth and Sudarshan


Inheritance & Reuse Engineering

 Method of reuse in which new functionality is


obtained by extending the implementation of an
existing object

 The generalization class (the superclass) explicitly


captures the common attributes and methods

 The specialization class (the subclass) extends the


implementation with additional attributes and
methods

Database System Concepts 3.14 ©Silberschatz, Korth and Sudarshan


Advantages/Disadvantages Of
Inheritance
 Advantages:
- New implementation is easy, since most of it is inherited
- Easy to modify or extend the implementation being reused

 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

Database System Concepts 3.15 ©Silberschatz, Korth and Sudarshan


Use inheritance only when all of the following
are satisfied:
 A subclass expresses "is a special kind of" and not "is a
role played by a“
a

 An instance of a subclass never needs to become an


object of another class

 A subclass extends, rather than overrides or nullifies, the


responsibilities of its superclass

 A subclass does not extend the capabilities of what is


merely a utility class

 For a class in the actual Problem Domain, the subclass


specializes a role,
role transaction or device
Database System Concepts 3.16 ©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.

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 ?

 Employee e; //This statement is OK.


 e = new Employee(“George W.”, “Houston, TX”, 43);

 No. It will give Compilation error.


 Though we can still create Employee references, such as
the reference e in the previous statements; however, you
cannot use the new operator on Employee if the Employee
class is declared abstract.
Database System Concepts 3.19 ©Silberschatz, Korth and Sudarshan
Abstraction
.
 If it is asked to you to draw a picture of a mammal, you would
likely draw a dog, horse, person, or something similar.
 If I asked you to draw a picture of something that was just a
mammal, you can see how the concept of a mammal is abstract.
 Many animals are mammals, but no animal is just a mammal. It
seems logical, therefore, that no one would need to instantiate
an object of type Mammal (assuming that we wrote a Mammal
class).
 Similarly, all of our employees in our company are of type Employee,
but no one is just an
 Employee.
 It seems logical that no one would need to instantiate an object
of type Employee, and it should be declared abstract.

Database System Concepts 3.20 ©Silberschatz, Korth and Sudarshan


Abstract Methods

Abstract Methods do not provide implementations


and a Class that contains any abstract methods
must be declared as Abstract Class even if that
Class contains some concrete (nonabstract )
methods.

 If you want a class to contain a particular method


but you want the actual implementation of that
method to be determined by child classes, you can
declare the method in the parent class as abstract.

 Abstract methods consist of a method signature,


but no method body.

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
}

 You can still create Employee references, such as the


reference e in the previous statements; however, you cannot
use the new operator on Employee if the Employee class is
declared abstract.

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.”

 Grady Booch: “An abstraction denotes the essential


characteristics of an object that distinguish it from all other
kinds of objects and thus provide crisply defined conceptual
boundaries, relative to the perspective of the viewer.”

 Abstraction is one of the fundamental ways to deal with


complexity

 An abstraction focuses on the outside view of an object and


separates an object’s behavior from its implementation

Database System Concepts 3.23 ©Silberschatz, Korth and Sudarshan


24
Database System Concepts 3.24 ©Silberschatz, Korth and Sudarshan
What Is an Interface?
 As we've already learned, objects define their interaction with
the outside world through the methods that they expose.
 Methods form the object's interface with the outside world;
 the buttons on the front of your television set, for example, are
the interface between you and the electrical wiring on the other
side of its plastic casing. You press the "power" button to turn
the television on and off.
 In its most common form, an interface in OOPS is a group of
related methods with empty bodies.
 An interface is a collection of abstract methods.
 A class implements an interface, thereby inheriting the
abstract methods of the interface.
 Unless the class that implements the interface is abstract, all
the methods of the interface need to be defined in the class.

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:

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode
file must be in a directory structure that matches the package
name.

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;

 an interface can be used to expose certain


behaviors of a class, without exposing all of
the behaviors of a class.
 Interfaces can be used to force behavior
on other objects, ensuring that certain
methods are implemented by an object.
 Interfaces can be used for polymorphism
reasons, since an object can take on the
form of an interface type.

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.

 An  abstract class may contain non-final variables.


 Members of a Java interface are public by default.

 A Java abstract class can have the usual flavors of


class members like private, protected, etc.
 Java interface should be implemented using keyword
“implements”;
 A Java abstract class should be extended using
keyword “extends”.

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;

 A Java abstract class also cannot be instantiated,


but can be invoked if a main() exists.
 In comparison with java abstract classes, java interfaces are
slow as it requires extra indirection.

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

 After this the marks will be submitted to Exam


Cell for records and is not liable to changed
afterwards.

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

 Project with Java: GUI & Applets


 Using AWT & Swing
 Event Handling in Java : Delegation model
 Event Source , Listener & Interface

 Applets & Standalone applications: Writing Applet


 Embedding in HTML

 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.:

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above example:
 A Deer IS-A Animal
 A Deer IS-A Vegetarian
 A Deer IS-A Deer
 A Deer IS-A Object

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.

Database System Concepts 3.37 ©Silberschatz, Korth and Sudarshan


Common Interfaces of Java API
 The Java platform provides an enormous class library (a set
of packages) suitable for use in your own applications.
 This library is known as the "Application Programming
Interface", or "API" for short.
 Its packages represent the tasks most commonly
associated with general-purpose programming.
 The Java Platform API Specification contains the complete
listing for all packages, interfaces, classes, fields, and
methods supplied by the Java Platform 6, Standard Edition.
(http://download.oracle.com/javase/6/docs/api/index.html )
 Load the page in your browser and bookmark it. As a
programmer, it will become your single most important
piece of reference documentation.

12/08/21 38
Database System Concepts 3.38 ©Silberschatz, Korth and Sudarshan
Common Interfaces of Java API

 Java provides several powerful and flexible


common interfaces as API .
 These interfaces are implemented and used in
the same manner as the normal interfaces.
 To enable the interface use your own class
within the framework provided by the Java.
 Some of the interfaces available in Java are
Comparable, Serializable, Runnable, GUI
event-listener interfaces and SwingConstants.

Database System Concepts 3.39 ©Silberschatz, Korth and Sudarshan


Java APIs
 The Java API contains hundreds of interfaces.

 The Runnable interface is used when


writing multithreaded applications.
 The MouseListener interface is another
example of an interface in the Java API. It
is defined in the java.awt.event package
and contains five methods

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.

Database System Concepts 3.41 ©Silberschatz, Korth and Sudarshan


Example:

If class Employee implements Comparable, its


compareTo method could compare Employee object
by their earning amounts. Interface Comparable is
commonly used for ordering objects in a collection
such as an array.

Database System Concepts 3.42 ©Silberschatz, Korth and Sudarshan


Serializable:
An interface used to identify classes whose objects can be
return to ( ie serialize) are read from (ie deserialize) some
type of storage( eg file on disk, data base field) or
transmitted across a network.

Database System Concepts 3.43 ©Silberschatz, Korth and Sudarshan


Runnable:
Implemented by any class for which objects of that class
should be able to execute in parallel using a technique
called multithreading. The interface contains one method,
run, which describes the behavior of an object when
execute.

Database System Concepts 3.44 ©Silberschatz, Korth and Sudarshan


GUI event-listener interfaces:
In web browser one may type in a text field, the address of a
website to visit, or might click a button to return to the
previous site visited. The browser will respond to the
interaction and performs the desired task, this interaction is
known as event and the code the browser uses to respond to an
event is known as event handler. The event handlers are
declared in classes that implement an appropriate event-
listener interface. Each event-listener interface specifies one
or more methods that must be implemented to respond to user
interaction.

Database System Concepts 3.45 ©Silberschatz, Korth and Sudarshan


SwingConstants:
It contains a set of constants used in GUI programming to
position GUI elements on the screen.

Database System Concepts 3.46 ©Silberschatz, Korth and Sudarshan


MouseListener interface
package java.awt.event;
public interface MouseListener extends  MouseListener interface
java.util.EventListener has a parent interface
named EventListener.
{
public void mouseClicked(MouseEvent m); Any class that implements
MouseListener must also
public void mouseEntered(MouseEvent m); implement the methods of
public void mouseExited(MouseEvent m); EventListener;
EventListener however,
EventListener does not
public void mousePressed(MouseEvent contain any methods:
m);
public void mouseReleased(MouseEvent package java.util;
public interface
m);
EventListener
} {}
 Any class implementing MouseListener
needs to implement all five of these
methods.
47
Database System Concepts 3.47 ©Silberschatz, Korth and Sudarshan
User-Defined Interfaces
 You can also write your own interfaces. The following
PhoneHandler interface is a user-defined interface that contains
three methods:
package customer.service;
public interface PhoneHandler
{
public void answer();
public boolean forward(int extension);
public void takeMessage(String message, String recipient);
}
The PhoneHandler interface must be saved in a file named
PhoneHandler.java, and the bytecode file PhoneHandler.class
needs to appear in a \customer\service directory.

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

 Because Rectangle is neither declared abstract,


nor implements the paint() method in Paintable,
we will get the compilation error.
 If we want a quick fix for our Rectangle class,
simply declare it as abstract:
 public abstract Rectangle implements
Paintable
 It will compile now, but you will not be able to
create any Rectangle objects because it is an
abstract class.
 Add the paint() Method

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.

 It should compile successfully this


time.

 You have now written both an


interface and a class that
implements the interface.
 Next, you can write a class that
paints Paintable objects, and we
can use the Rectangle class as an
example.

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

 Administrative and ownership reasons


 Heterogeneous systems
 Shared by multiple applications
 Scalability

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 a t a S p e c ia lis t s FRO NT END BACK END


- - > M o d e le r (V B , V C + + , J A V A ) ( O r a c le ,
- - > A r c h it e c t S Q L -S e rv e r, D B -2 )

D e v e lo p e r s DBAs

Database System Concepts 3.59 ©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.

Although there are several techniques for creating GUI but


let us explore GUI creations by Java .
 In Java Graphical User Interface (GUI) programming, we
do not build GUI components from scratch. Instead we
use GUI components provided to us by the JDK. 

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.

Although there are several techniques for creating GUI but


let us explore GUI creations by Java .
 In Java Graphical User Interface (GUI) programming, we
do not build GUI components from scratch. Instead we
use GUI components provided to us by the JDK. 

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

 Components & Containers


 Frame Classes
 Layout Managers

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

 Frame to represent a typical window,


 Button to represent buttons,
 Menu to represent a window’s menu,
and so on.

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

 The basic starting point of a GUI is the container because


you need a container before you can start laying out your
components.
 The java.awt.Frame and javax.swing.JFrame classes are
containers that represent a basic window with a title bar and
common windowing capabilities such as resizing,
minimizing, maximizing, and closing.
 The Frame class is used for AWT programs and is the
parent class of JFrame, which is used for Swing programs.

12/08/21 69
Database System Concepts 3.69 ©Silberschatz, Korth and Sudarshan
GUI Coordinates

 All components and containers have a size and


location, which is denoted in pixels.
 A pixel is a relative unit of measurement based
on the settings of the user’s screen.
 The pixels create a coordinate system, with the
upper-left corner of the screen as the origin (0,0).
 Any point on the screen can be represented as an
(x,y) value, where x is the number of pixels to the
right of the origin, and y is the number of pixels
down from the origin.

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:

I. public Frame(). Creates a new frame with no message in the


title bar.
II. public Frame(String title). Creates a new frame with the
given String appearing in the title bar.
III. public Frame(GraphicsConfiguration gc). Creates a frame
with the specified GraphicsConfiguration of a screen device.
IV. public Frame(String title, GraphicsConfiguration gc).
Creates a frame with the specified title and
GraphicsConfiguration.

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:

public void setVisible(boolean show)


 If the boolean passed in is true, the component is made
visible. If the value is false, the component is hidden.

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

We can move, resize, minimize, and maximize


the Frame window.
However, we can’t close the window because closing
a window often implies ending the program.
If the user needs to save a
document or other settings before ending, your program needs a chance
to do this.
The closing involves handling the WindowEvent generated by a user attempting
to
close the 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

 GUI & Applet in Java: Event Handling in Java


 Using AWT & Swing
 Event Handling in Java : Delegation model
 Event Source , Listener & Interface

 Applets & Standalone applications: Writing Applet


 Embedding in HTML

 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:-

1) The source of the event.


event In GUI programming, the component is
the source of the event. Events are Java objects that are
instantiated by the component and passed as an argument to
any listeners.
2) An event listener.
listener A listener of an event registers itself with the
source of the event. When an event occurs, the source of the
event invokes a method on the listener.
3) An interface.
interface The interface contains the methods that the listener
must implement and that the source of the event invokes when
the event occurs.

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.

Database System Concepts 3.97 ©Silberschatz, Korth and Sudarshan


Event Listener Interfaces
 Java uses a standard naming convention for event classes
and listener interfaces:
 The name of the event class uses the
convention <Name>Event, and
 the corresponding listener interface
uses the convention <Name>Listener.
Listener
 For example, the ActionEvent class is associated with the
one method of the ActionListener interface, and the
WindowEvent class is associated with the seven methods of
the WindowListener 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

 An applet is a Java class; if the applet is to be viewed


in a Web browser, the class must extend the
java.applet.Applet class.
 The Applet class provides a common interface so that
a Web browser can communicate with the applet.
 The intersting note about the Applet class is that it
extends java.awt.Panel.
 Panel is the simplest container class. A panel
provides space in which an application can attach any
other component, including other panels.

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:

 Code: The name of the applet class for


this applet.
 Width: The width in pixels of the applet.
 Height: The height in pixels of the applet.
 For example, if the name of your applet class is
com.world.MyApplet, the following HTML embeds an instance of
MyApplet in a Web page:
<applet code=”com.world.MyApplet” width=”400” height=”500”>
</applet>
 The size of the applet will be 400 pixels wide and 500 pixels
high.

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)

Database System Concepts 3.123 ©Silberschatz, Korth and Sudarshan


Design Patterns Overview
 In software engineering, a design pattern is a general reusable
solution to a commonly occurring problem in software design.
 A design pattern is not a finished design that can be transformed
directly into code. It is a description or template for how to solve a
problem that can be used in many different situations.
 Object-oriented design patterns typically show relationships and
interactions between classes or objects, without specifying the
final application classes or objects that are involved.
 Design patterns reside in the domain of modules and
interconnections.
 At a higher level there are architectural patterns that are larger in
scope, usually describing an overall pattern followed by an entire
system.
 Not all software patterns are design patterns. For instance,
algorithms solve computational problems rather than software
design problems.

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

 Design patterns can speed up the development process by


providing tested, proven development paradigms.
 Effective software design requires considering issues that may not
become visible until later in the implementation.
 Reusing design patterns helps to prevent subtle issues that can
cause major problems, and it also improves code readability for
coders and architects who are familiar with the patterns.
 Design Patterns proposed in the popular Book
 Authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides
with a foreword by Grady Booch. They are often referred to as the Gang of
Four, or GoF.
 Describing 23 classic software design patterns.
patterns
 Regarded as an important source for object-oriented design theory and
practice. More than 500,000 copies have been sold in English and in 13 other
languages.

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

Adhere to 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

 Implementations

128
Database System Concepts 3.128 ©Silberschatz, Korth and Sudarshan
Open Closed Principle

 Software entities like classes, modules and functions


should be open for extension but closed for modifications.
 OPC is a generic principle. You can consider it when writing
your classes to make sure that when you need to extend
their behavior you don’t have to change the class but to
extend it.
 The same principle can be applied for modules, packages,
libraries. If you have a library containing a set of classes
there are many reasons for which you’ll prefer to extend it
without changing the code that was already written
(backward compatibility, regression testing, …).
 This is why we have to make sure our modules follow 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!

Database System Concepts 3.132 ©Silberschatz, Korth and Sudarshan


Benefits Of Interfaces
Advantages:
 Clients are unaware of the specific class of the object
they are using
 One object can be easily replaced by another
 Object connections need not be hardwired to an
object of a specific class, thereby increasing flexibility
 Loosens coupling
 Increases likelihood of reuse
 Improves opportunities for composition since contained
objects can be of any class that implements a specific
interface
Disadvantages:
 Modest increase in design complexity

Database System Concepts 3.133 ©Silberschatz, Korth and Sudarshan


The Liskov Substitution Principle

 Liskov's Substitution Principle was introduced by Barbara


Liskov in a 1987 Conference on Object Oriented
Programming Systems Languages and Applications, in Data
abstraction and hierarchy

 This principle is just an extension of the Open Close


Principle in terms of behavior meaning that we must make
sure that new derived classes are extending the base
classes without changing their behavior.

 The new derived classes should be able to replace the base


classes without any change in the code.

Database System Concepts 3.134 ©Silberschatz, Korth and Sudarshan


The Liskov Substitution Principle
 It states that, if S is a subtype of T, then objects of type T in
a computer program may be replaced with objects of type S
(i.e., objects of type S may be substituted for objects of type T),
without altering any of the desirable properties of that
program (correctness, task performed, etc.).

 If a class S is a subtype of class T, then a class T in a software


design can be substituted with a class S without altering any of
the desirable properties and behaviour of that software design.

 Functions That Use References To Base (Super) Classes Must


Be Able To Use Objects Of Derived (Sub) Classes Without
Knowing It.

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.

Database System Concepts 3.136 ©Silberschatz, Korth and Sudarshan


137
Database System Concepts 3.137 ©Silberschatz, Korth and Sudarshan
The Liskov Substitution Principle
 Inheritance is usually described as an "is a"
relationship to avoid incorrect use.
 The "is a" technique of determining inheritance
relationships is simple and useful, but occasionally
results in bad use of inheritance.
 The Liskov Substitution Principle is a way of ensuring
that inheritance is used correctly.
 If a function does not satisfy the LSP, then it probably
makes explicit reference to some or all of the
subclasses of its superclass.
 Such a function also violates the Open-Closed
Principle, since it may have to be modified whenever a
new subclass is created.

Database System Concepts 3.138 ©Silberschatz, Korth and Sudarshan


The Liskov Substitution Principle
 The Liskov Substitution Principle (LSP) seems obvious
given all we know about polymorphism
 For example:

public void drawShape(Shape s) {


// Code here.
}

 The drawShape method should work with any subclass of


the Shape superclass (or, if Shape is a Java interface, it
should work with any class that implements the Shape
interface)

 But we must be careful when we implement subclasses to


insure that we do not unintentionally violate the LSP

Database System Concepts 3.139 ©Silberschatz, Korth and Sudarshan


LSP:The Square and Rectangle problem
 Most people would think that a
Square is a special kind of
Rectangle and therefor
intuitively inherit their Square
class from the Rectangle class
to be able to reuse code.
 However if you study the given
image you will notice that the  And this fact may for some
Rectangle have a couple of traits problems be quite tricky to
that the Square does NOT and discover sometimes. And if
vice versa. you do the capital sin of
 First of all the Square has only inheriting your Square class
*ONE* attribute; size, while the
from your Rectangle class,
Rectangle have *TWO* ……
attributes; width & height.

140
Database System Concepts 3.140 ©Silberschatz, Korth and Sudarshan
LSP Example
 Consider the following Rectangle class:

public class Rectangle {


private double width;
private double height;
public Rectangle(double w, double h) {
width = w;
height = h;
}
public double getWidth() {return width;}
public double getHeight() {return height;}
public void setWidth(double w) {width = w;}
public void setHeight(double h) {height = h;}
public double area() {return (width * height);
}

Database System Concepts 3.141 ©Silberschatz, Korth and Sudarshan


LSP Example Continued
 Now, how about a Square class? Clearly, a square is a
rectangle,
rectangle so the Square class should be derived from the
Rectangle class

Observations:

 A square does not need both a width and a height as


attributes, but it will inherit them from Rectangle anyway.
So, each Square object wastes a little memory, but this is
not a major concern.
 The inherited setWidth() , setHeight() methods are not really
appropriate for a Square, since the width and height of a
square are identical.

 So we'll need to override setWidth() and setHeight

Database System Concepts 3.142 ©Silberschatz, Korth and Sudarshan


LSP Example Continued
 Here's the Square class:

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

Database System Concepts 3.143 ©Silberschatz, Korth and Sudarshan


LSP Example Continued
 Check this out!

public class TestRectangle {


// Define a method that takes a Rectangle reference.
public static void testLSP(Rectangle r) {
r.setWidth(4.0);
r.setHeight(5.0);
System.out.println("Width is 4.0 and Height is 5.0" + ", so Area is
" + r.area());
if (r.area() == 20.0)
System.out.println(“OK!\n");
else
System.out.println(“Error!\n");
}

Database System Concepts 3.144 ©Silberschatz, Korth and Sudarshan


LSP Example Continued
public static void main(String args[ ]) {
//Create a Rectangle and a Square
Rectangle r = new Rectangle(1.0, 1.0);
Square s = new Square(1.0);
// Now call the method above. According to the
// LSP, it should work for either Rectangles or
// Squares. Does it??
testLSP(r);
testLSP(s);
}
}

Database System Concepts 3.145 ©Silberschatz, Korth and Sudarshan


 Test program output:

Width is 4.0 and Height is 5.0, so Area is 20.0


OK!
Width is 4.0 and Height is 5.0, so Area is 25.0
Error!
 Looks like we violated the LSP!

Database System Concepts 3.146 ©Silberschatz, Korth and Sudarshan


LSP Example: Observation
 A mathematical square might be a rectangle, but a
Square object is not a Rectangle object.
 Behavior of a Square object is not consistent with the
behavior of a Rectangle object!
 Behaviorally,
Behaviorally a Square is not a Rectangle!
Rectangle A Square
object is not polymorphic with a Rectangle object.
 If you inherit your Square class from your Rectangle
class, then you might currently get around it by hiding
the width property of the Rectangle somehow, maybe
by convention, and then just let the size property of
the Square forward the call to height or something
similar, but this is always wrong!
 Having to override these simple methods is a clue that
this might not be an appropriate use of inheritance!

Database System Concepts 3.147 ©Silberschatz, Korth and Sudarshan


LSP & Programming Languages
 The problem is when you hit "real life scenarios",
especially with Single Inheritance programming
languages - like for instance C# and Java.
Java

 Because if you're not supposed to break LSP you

will often tend to repeat code a LOT.


 In C# you cannot inherit from multiple classes like
you can in C and other MI (Multiple Inheritance
languages) you cannot create "small, lightweight
carrier classes" for you to inherit from to not
break LSP !

148
Database System Concepts 3.148 ©Silberschatz, Korth and Sudarshan
OOSE Design Principles
 OOM characteristics & implementation

 Inheritance, Encapsulation & Polymorphism


 Child Class referencing with Parent Class
type
 Instantiating new objects in Java

 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.:

public interface Vegetarian{}


public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now the Deer class is considered to be polymorphic since this has multiple
inheritance. Following are true for the above example:
 A Deer IS-A Animal
 A Deer IS-A Vegetarian
 A Deer IS-A Deer
 A Deer IS-A Object

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.

Database System Concepts 3.151 ©Silberschatz, Korth and Sudarshan


Java Primitive data types

 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

 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.
 This concept is a very important part of the
polymorphism portion of object-oriented
programming (OOP).

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:

Object instanceof type


 Here object is an instance of a class, and type is a class
type.
 If object is of the specified type or can be cast into the
specified type, then the instanceof operator evaluates to
true.
 Otherwise its result is false.

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

 Having an Employee parameter makes payEmployee() a


more generic method in that its parameter is loosely
defined.
 Presently, it can accept Employee, Hourly, and Salary
objects.
 If a new class came along that extended Employee, say a
class named Contractor, Contractor objects could also be
passed in to payEmployee().

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

 We can use the concept of Virtual methods to show a


payEmployee() method that can pay all Employee objects
without requiring modification when new child classes of
Employee come along.

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.

 This concept is a very important part of the


polymorphism portion of object-oriented
programming (OOP).
 In Java all the method is by default virtual methods
and the overriding is done at run-time.
 What to do so as to make an method in Java to be
non-virtual method ?

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

También podría gustarte