The java language and environment
Download
1 / 100

- PowerPoint PPT Presentation


  • 239 Views
  • Updated On :

The Java Language and Environment. Cecilia Bastarrica, Anupama Vadali, and Prof. Steven A. Demurjian, Sr. Computer Science & Engineering Department The University of Connecticut 371 Fairfield Road, Box U-255 Storrs, CT 06269-2155. [email protected] http://www.engr.uconn.edu/~steve

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about '' - bairn


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
The java language and environment
The Java Language and Environment

Cecilia Bastarrica, Anupama Vadali, and

Prof. Steven A. Demurjian, Sr.

Computer Science & Engineering Department

The University of Connecticut

371 Fairfield Road, Box U-255

Storrs, CT 06269-2155

[email protected]

http://www.engr.uconn.edu/~steve

http://www.engr.uconn.edu/cse

(860) 486 - 4818


Overview of presentation
Overview of Presentation

  • Motivation and Introduction to Java

  • Designing and Developing Applets in Java

  • The Java User Interface - GUI with AWT

  • Designing and Developing Java Classes

  • Inheritance and Interfaces in Java

  • Polymorphism and Object Serialization


Motivation and introduction to java
Motivation and Introduction to Java

  • Java is Emerging as the OO Language of Choice

  • Java’s Utilization in …

    • Distributed Internet-Based Applications of All Types

    • Legacy/COTS Integration for Enterprise Computing

    • General-Purpose, Single-CPU Development

  • Significant Dissemination on WWW:

    • http://www.javasoft.com

    • http://www.gamelan.com

  • We’ll Overview Key Features and Capabilities


An overview of java
An Overview of Java

  • Java is a Third Generation, General Purpose, Platform Independent, Concurrent, Class-Based, Object-Oriented Language and Environment

  • Java Composed of JDK and JRE

    • Java Language

    • Java Packages (Libraries)

    • javac Compiler to Bytecode (p-code)

    • JDB Java Debugger

    • Java Interpreter - Platform Specific

  • JDK: Java Development Environmenthttp://www.javasoft.com/products/jdk/1.2/

  • JRE: Java Runtime Environmenthttp://www.javasoft.com/products/jdk/1.2/jre/index.html


What is java software releases and ides
What is Java?Software Releases and IDEs

  • Java is Free!

  • Current Releases

    • Version 2 for Win95, Win98, NT

    • Version 2 (Early Access) for Solaris

  • Third-Party Ports to All Conceivable HW/SW Platforms from Micros to Mainframes http://www.javasoft.com/cgi-bin/java-ports.cgi

  • Integrated Development Environments (IDEs)

    • Commercial Products, Freeware, Visual IDEs

    • Visual J++, Visual Café, Kawa, Jpad, Javelin


Java virtual machine jvm
Java Virtual Machine (JVM)

  • JVM is a Platform Specific Program which Interprets and Executes Java Code

  • JVM Interprets and Executes Bytecodes

  • JVM Targeted as Small/Efficient - Embeddable within Consumer Electronics

  • JVM Stack Based Machine - Simulates Real Processor

CA FE BA BE 00 03 00 2D 00 3E

08 00 3B 08 00 01 08 00 20 08



Packages in java
Packages In Java

  • Allows Related Classes to be Grouped into a Larger Abstraction

    • Similar to Ada95 Packages

    • Unavailable in C++

  • Utilization of Packages for SW Design and Development

    • Components, Modularization, Groupings

    • Enforcement by Compiler of Package Rules

  • Overall, Packages Enhance the Control and Visibility to Fine-Tune

    • Who Can See What When


The java api packages
The Java API Packages

  • Application Programming Interface (API)

  • Java Defined - Building Blocks/Libraries

  • Java Platform 1.2/2 Core API

    java.applet java.rmi

    java.awt java.rmi.dgc

    java.awt.datatransfer java.rmi.registry

    java.awt.event java.rmi.server

    java.awt.image java.security

    java.beans java.security.acl

    java.io java.security.interfaces

    java.lang java.sql

    java.lang.reflect java.text

    java.math java.util

    java.net java.util.zip

  • Power of Java Contained with APIs


The java language
The Java Language

  • Overview of Non-OO Capabilities

    • Based on C/C++

    • No includes, typedefs, structures, groups

    • Unicode Character Set - 34,168 Characters

    • Automatic Coercions Not Supported

    • Strongly-Type Language

  • Variables in Java

    • Primitive Types: ints, floats, booleans, Unicode chars

    • Reference Types: arrays, classes, interfaces

  • No Physical Pointers in Java!


The java language1
The Java Language

  • Statements in Java - Resembles C and C++

    • Assignment/Expressions and Precedence

    • for, while, do-while

    • if-then, switch-case

    • break, continue, label, return

  • Exception Handling

    • Similar to C++

    • try, throws, catch Blocks

    • Strongly Integrated Throughout APIs


The java language motivating the class concept
The Java LanguageMotivating the Class Concept

  • Conceptually, Classes are Structures/Records with Functions that are Encapsulated

structure Item

{ int UPC, OnShelf, InStock, ROLimit;

char* Name;

float RCost, WCost;

Status Create_New_Item(int UPC, ...);

NameCost* Get_Item_NameCost(int UPC);

void Modify_Inventory(int UPC, int Delta) ;

Boolean Check_If_On_Shelf(int UPC);

Boolean Time_To_Reorder(int UPC);

};

NameCost *nc;

Item I1, I2;

I1.Create_New_Item(...);

nc = I2.Get_Item_NameCost(UPC);


The java language object oriented features
The Java LanguageObject-Oriented Features

  • Class - similar to C++ Class

  • Classes have Members (Methods and Variables)

  • Members Tagged Using Keywords

    • private: Typically, Inaccessible

    • public: Potential to be Accessible

    • protected: Accessible via Inheritance

    • package: Accessible within Package

  • Involve Visible Between Classes, Within Packages, and Due to Inheritance


Classes in java
Classes in Java

  • A Supermarket Item

  • Keywords must be Utilized for Each Attribute or Method Declaration

class Item {

private String UPC, Name;

private int Quantity;

private double RetailCost;

protected double WholeCost;

public Item() { ... };

public void finalize() { ... };

public boolean Modify_Inventory(int Delta){...};

public int Get_InStock_Amt()

{return Quantity;};

};


Classes in java1
Classes in Java

class Item {

private String UPC, Name;

private int Quantity;

private double RetailCost;

protected double WholeCost;

public Item() { ... };

public void finalize() { ... };

public boolean Modify_Inventory(int Delta)

{ int i = Get_InStock_Amt ();

if (Delta >= 0) {

Quantity += Delta;

return true;

} else { return false;} };

public int Get_InStock_Amt() {return Quantity;};

public double Compute_Item_Profit() {...};

protected boolean Modify_WholeSale(); {...};

};


Visibility of attributes methods
Visibility of Attributes/Methods

  • Class Members (Attributes and Methods)

  • Visibility Tags for Members

    • Private: Visible only to Class

    • Protected: Visible to Class and Other Classes within Package

    • Public: Visible to Class, Other Classes within Package, and if Class is Public, Visible to Other Packages/Classes

    • No Tag: Visible Only to Other Classes within Defining Package

  • Java's Controlled Sharing within/between Packages not Supported in C++

  • Abstraction/Encapsulation Superior in Java!


Inheritance two roles
Inheritance - Two Roles

  • Controlled Sharing Between Classes

    • Generalization vs. Specialization

  • Treat Instances of Different Classes in a Uniform Fashion

    • Polymorphism and Dynamic Binding

  • Inheritance in Java

Item

/ \

DeliItem ProduceItem

|

SaladItem

class DeliItem extends Item { ... };

class SaladItem extends DeliItem { ... };

class ProduceItem extends Item { ... };


Designing and developing applets in java
Designing and Developing Applets in Java

  • Applets Small Independent Programs Intended for Embedding into WWW Pages and Executable via Java-Enabled Browser (Netscape or IE)

  • Applets Operate Under Severe Security Limits:

    • Can’t Execute Local Programs

    • Can’t Communicate with Host Other than one from Which Downloaded

    • Can’t Read/Write to Local File System

    • Can’t Find Information on Local System Except Java/OS Versions and Character/Line Separators


Designing and developing applets in java1
Designing and Developing Applets in Java

  • An Applet is a Java Program that Executes as part of an HTML Page

applet

A.java

HTML file

...

<APPLET CODE = “A.class”>

...

javac

applet

A.class


Applets inheritance structure
Applets Inheritance Structure

java.lang.Object

java.awt.Component

java.awt.Container

java.applet.Applet

your applet

Everything in Java inherits from the Object class

Event-handling and drawing capabilities

Ability to hold components

Limits what an Applet can and cannot do

Every Applet is a subclass of the Applet class.


Applet methods eligible for overriding
Applet Methods Eligible for Overriding

Methods for Milestones

  • init - initializes an applet when it is loaded

  • start - (re)starts applet’s execution

  • stop - stops applet’s execution

  • destroy - final cleanup before unloading

Methods for Drawing

  • paint

  • update

The applet subclass must override at least one of these methods: init, start or paint.


Handling events

Applets Handle Events by Implementing the Corresponding interface

import java.awt.event.MouseListener;

import java.awt.event.MouseEvent;

public class Simple extends Applet

implements MouseListener {

public void init() {

addMouseListener(this);

}

public void mouseClicked(MouseEvent event) {

addItem(“click…”);

}

}

Handling Events

mouseClicked

mouseEntered

mouseExited

mousePressed

mouseReleased

Protocol of behavior

All methods in the interface must be implemented


Running an applet in html
Running an Applet in HTML

<APPLET CODE = “AppletSubclass.class” WIDTH = anInt HEIGHT = anInt>

</APPLET>

The Browser:

  • Reserves a Display Area for the Applet

  • Loads the bytecode

  • Creates an Instance of the Subclass

  • Calls the init and start Methods


Loading an applet
Loading an Applet

  • Finding an Applet

    • CODEBASE

    • Relative/Absolute Address

      CODEBASE=“example/”

      CODEBASE=“http://someServer/…/otherDirectory/”

  • Bringing the Applet

    • Class by Class/Archives

otherDirectory

example

HTML

file

HTML

file

Class

file

Class

file


The applet tag
The <APPLET> tag

<APPLET

[CODEBASE = codebaseURL]

(CODE = appletFile | OBJECT = serializedApplet)

[ARCHIVE = archivesList]

[ALT = alternateText]

[NAME = appletInstanceName]

WIDTH = pixelsHEIGHT = pixels

[ALIGN = alignment]

[VSPACE = pixels] [HSPACE = pixels]

>

[<PARAMNAME = appletParameter1VALUE = value>]

[<PARAMNAME = appletParameter2VALUE = value>]

[alternateHTML]

</APPLET>


Security issues
Security Issues

  • An Untrusted Applet Cannot:

    • Load Libraries or Define Native Methods

    • Read or Write Files on the Host that is Executing the Applet

    • Make Network Connections Except to the Host from Which it was Loaded From

    • Start any Program on the Host that is Executing the Applet

    • Get Many System Properties


Example of a gui applet
Example of a GUI Applet

/* http://java.sun.com/docs/books/tutorial/ui/components/example/

ButtonDemo.java */

import java.awt.*;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.applet.Applet;

public class ButtonDemo extends Applet

implements ActionListener {

Button b1, b2, b3;

static final String DISABLE = "disable";

static final String ENABLE = "enable";

public void init() {

b1 = new Button();

b1.setLabel("Disable middle button");

b1.setActionCommand(DISABLE);

b2 = new Button("Middle button");

b3 = new Button("Enable middle button");

b3.setEnabled(false);

b3.setActionCommand(ENABLE);


Example of a gui applet continued
Example of a GUI Applet (Continued)

//Listen for actions on buttons 1 and 3.

b1.addActionListener(this);

b3.addActionListener(this);

//Add Components to the Applet, using the default FlowLayout.

add(b1);

add(b2);

add(b3);

}

public void actionPerformed(ActionEvent e) {

String command = e.getActionCommand();

if (command == DISABLE) { //They clicked "Disable middle button"

b2.setEnabled(false);

b1.setEnabled(false);

b3.setEnabled(true);

} else { //They clicked "Enable middle button"

b2.setEnabled(true);

b1.setEnabled(true);

b3.setEnabled(false);

}

}

}


The java user interface gui with awt
The Java User Interface - GUI with AWT

  • UI Refers to the Communications Between a Program and a User

  • Java Abstract Windowing Toolkit (AWT) and Swing Contains Complete Set of Classes for Writing GUI Programs

  • AWT Classes Categorized into:

    • GUI Components

    • Containers

    • Layout Managers

    • Drawing

    • Event Handling


Awt components
AWT Components

  • Button

  • CheckBoxes

  • Choices

  • Lists

  • Menus

  • Textfields

  • Text Areas

  • Labels


Containers
Containers

  • The Java AWT Provides Three Types of Containers Implemented as Subclasses of Container Class:

    • Window

      • Frame - creates a normal full fledged window to contain components

      • Dialog - provides a window that is dependent on another window

      • FileDialog - helps the user to open and save file

    • Panel - Groups Components within an Area of an Existing Window

    • ScrollPane -Like Panel, Used to Display Large Component in a Limited Amount of Space



Layout managers
Layout Managers

  • Layout Manager Controls the Size and Position of Components in a Container

  • By Default Every Container Object has an Associated LayoutManger

    • Panel Objects - FlowLayout

    • Window Object - BorderLayout


Layout managers simple
Layout Managers - Simple

  • FlowLayout

    • Default for Panel Objects

    • Lays out Components from Left to Right Starting New Rows if Needed

  • GridLayout

    • Displays the Components in Equal Size in the Requested Number of Rows and Columns


Layout managers special purpose
Layout Managers - Special Purpose

  • BorderLayout

    • Default for Window Objects

    • Uses 5 Areas to hold Components: North, South, East, West, and Center

  • CardLayout

    • One Area Contains Different Components at Different Times


Layout managers flexible
Layout Managers - Flexible

  • GridBagLayout

    • Aligns Components by Placing them in a Grid of Cells

    • Allows some Components to Span more than one Cell

    • The Rows and Columns have Different Heights and Widths


Example of a gui applet1
Example of a GUI applet

TextField

Name

TextArea

Address

Label

Order Now

CheckBox

Size

Choices

Color

OK

Cancel

Quit

Button


Excerpts for gui applet example note many lines omitted
Excerpts for GUI Applet Example(Note: Many Lines Omitted!!)

import java.applet.*;

import java.awt.*;

import Message;

public class Sample extends Applet

{ Panel p1, p2;

Label l1, l2, l3, l4, l5;

TextField name;

TextArea address;

Checkbox order;

Choice size, color;

Button ok, clear, quit ;

Message message;


Excerpts for gui applet example note many lines omitted1
Excerpts for GUI Applet Example (Note: Many Lines Omitted!!)

p1.setLayout(new

GridLayout(0,2,2,2));

p1.add(l1);

p1.add(name);

p1.add(l2);

p1.add(address);

p1.add(l3);

p1.add(order);

p1.add(l4);

p1.add(size);

p1.add(l5);

p1.add(color);

p2.setLayout(new

FlowLayout());

p2.add(ok);

p2.add(clear);

p2.add(quit);

setLayout(new

BorderLayout());

add("North", p1);

add("South", p2);

}

public void init()

{ p1 = new Panel();

p2 = new Panel();

l1 = new Label("Name");

l2 = new Label("Address");

// … other labels omitted

name = new TextField(30);

address = new TextArea(3, 30);

order = new Checkbox();

size = new Choice();

size.addItem("Small");

size.disable();

ok = new Button("OK");

clear = new Button("Clear");

quit = new Button("Quit");


Excerpts for gui applet example note many lines omitted2
Excerpts for GUI Applet Example (Note: Many Lines Omitted!!)

public boolean action(Event e, Object o)

{ if(e.target == ok)

{ // You must provide the actions/code

}

if(e.target == clear)

{ // You must provide the actions/code

}

if(e.target == quit)

{ // You must provide the actions/code

}

if(e.target == order)

{

if(order.getState() == true)

{ // You must provide the actions/code

}

else if(order.getState() == false)

{ // You must provide the actions/code

}

}

return true;

}

}


Event handling
Event Handling

  • When a User Acts on a Component, the AWT Detects the Event and Notifies the Event Listeners

  • A Class Implements the Event Listener and Every Class Instance can Register as Event Listeners

  • Steps for Implementing and Registering:

    • Declare that a Class Implements a Listener Interface in the Class declaration

    • Implement the Listener methods in the Class

    • Register an Instance of the Class as a Listener on One or More Components


Example of event handling
Example of Event Handling

public class Beeper ... implements ActionListener {

...

// where initialization occurs:

button.addActionListener(this);

...

public void actionPerformed(ActionEvent e) {

// Make a beep sound

...

}

}


The awt events
The AWT Events

  • Action Events

  • Adjustment Event

  • Component Events

  • Container Events

  • Focus Events

  • Item Events

  • Key Events

  • Mouse Events

  • Mouse-Motion Events

  • Text Events

  • Window Event


Action listeners
Action Listeners

  • Easiest Event Handlers to Implement

  • Generated by:

    • Clicking a Button

    • Double Clicking a List Item

    • Choosing a Menu Item

    • Pressing Return in a Text Field

  • Listener Interface - ActionListener

  • Methods - actionPerformed(ActionEvent)


Action listeners actionevent
Action Listeners - ActionEvent

  • Parameter to the actionPerfomed Method

  • ActionEvent Defines Two Useful Methods

    • String setActionCommand

      • Associates a string to the action

    • String getActionCommand

      • Returns the string associated with this action


Item listeners
Item Listeners

  • Generated by Components that Maintain State, Generally on/off State

  • Components that Generate ItemEvents:

    • Checkboxes

    • Choices

    • Lists

  • Listener Interface - ItemListener

  • Methods - itemStateChanged(ItemEvent)


Itemlisteners itemevent
ItemListeners - ItemEvent

  • Parameter to the itemStateChanged Method

  • ItemEvent Defines Two Useful Methods:

    • Object getItem()

      • Returns the component specific object associated with the item whose state has changed

    • int getStateChange()

      • Returns the new state of the item

      • SELECTED = 1

      • DESELECTED = 0


Excerpts for gui applet with listener note many lines omitted
Excerpts for GUI Applet with Listener(Note: Many Lines Omitted!!)

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

import Message;

public class Sample1 extends Applet implements ActionListener,

ItemListener

{

// Declarations similar to previous example

static final String OK = "ok";

public void init()

{ // Init actions similar to previous example,

// except for code shown below for checkbox and buttons

order = new Checkbox();

order.addItemListener(this);

ok = new Button("OK");

ok.setActionCommand(OK);

ok.addActionListener(this);

}


Excerpts for gui applet with listener note many lines omitted1
Excerpts for GUI Applet with Listener(Note: Many Lines Omitted!!)

public void actionPerformed(ActionEvent e)

{ String command = e.getActionCommand();

if(command == OK)

{ // You must provide the actions/code

}

if(command == CLEAR)

{ // You must provide the actions/code }

if(command == QUIT)

{ // You must provide the actions/code

}

}

public void itemStateChanged(ItemEvent e1)

{ if(e1.getStateChange() == ItemEvent.SELECTED)

{ // You must provide the actions/code

}

else

{ // You must provide the actions/code

}

}

}


Designing and developing java classes
Designing and Developing Java Classes

  • Encapsulation Capabilities of Java

    • Classes (Data + Operations) - ADTs

    • Packages - Collections of “Related” Classes

  • Class Declaration:

    • Access Modes and Variable Members

    • Constructors and Class Bodies

    • Method Declaration and Access Modes

    • Class and Instance Members

    • Garbage Collection


Class definition

public class Stack {

private Vector items;

public Stack() {

items = new Vector(10);

}

public Stack(int numElem) {

items = new Vector(numElem);

}

public Object push(Object item) {

item.addElement(item);

return item;

}

public synchronized Object pop() {

int len = items.size();

Object obj = null;

if (len == 0)

throw new EmptyStackException();

obj = items.elementAt(len - 1);

items.removeElementAt(len - 1);

return obj;

}

public boolean isEmpty() {

if (items.size() == 0)

return true;

else

return false;

}

}

Class Definition

Class Declaration

Member

Variable

Constructors

Class Body

Member

Methods


Packages
Packages

  • A package is a Collection of Related Classes and Interfaces that Provides Access Protection and Namespace Management

  • File Name and Package Name Identical

  • Packages are Imported via the import Keyword

    package graphics;

    class Circle extend Graphic implements Draggable

    {

    ...

    }

    class Rectangle extends Graphic implements Draggable

    {

    ...

    }

    interface Draggable {

    ...

    }


Access modes

Constructors and Members can be defined as:

public: Any other class can invoke them.

protected: Only subclasses and classes in the same package can invoke them.

private: Only accessible within the class.

package: Accessible only to other classes and interfaces declared in the same package (default if omitted).

Controls Encapsulation and Allows Evolvability with Minimal Impact on other Classes that use the Members

Deciding Appropriate Access Mode Determines Security and Ensures that Data Remains in a Consistent State.

Access Modes


Constructors
Constructors

  • Utilized to Create a new Class instance by Reserving Sspace for the Member Variables Rectangle rect = new Rectangle();Member Variable Initialization Possible

  • Constructors Mimic Class Name with No Return Type

  • Default Constructor with Empty Argument List

  • Constructors may be Overloaded


Variable members
Variable Members

  • Declaration (Class Body)

    • Defines the Type of a Variable

  • Instantiation (Constructor)

    • Reserves Memory for the New Instance

  • Initialization

    • Assign Initial Value(s)


Method members
Method Members

  • Declaration

    • Access Level

      • public, protected, private, or package

    • Return Type

      • void or type

      • return statement

      • Either return the declared type or a subtype

    • Name

      • Overloading

      • Overriding

    • Arguments

      • List of variable declarations

      • Cannot include methods

      • Argument names may hide member names: this



Example
Example

public class Point {

public int x = 0;

public int y = 0;

public void move(int newX, int newY) {

x = newX;

y = newY;

}

}

public class Line {

public Point origin;

public Point end;

public Line() {

origin = new Point();

end = new Point();

}

public Line(Point origin, Point end) {

this.origin = origin;

this.end = end;

}

}

aLineObject

Default

Constructor

Line

Instance

origin

end

x

y

x

y

Point

Instances

Overloading

Hiding


Class and instance members
Class and Instance Members

  • Class Members are Defined with the Keyword static

  • Class Variables and Class Methods are Associated with the Class Rather than each of its Instances

  • Class Variables are Shared Among all Instances

  • JRE Creates one copy of Class Variables the First Time it Encounters a Containing Instance

  • Class Methods only Operate on Class Variables

  • Class Bariables declared as final are constants

  • Class Members are Accessible without the need to Instantiate the Class

    className.classMethod();

    className.classVar = 10;


Class and instance members continued

class AnInteger {

int x;

public int x() {

return x;

}

public void setX(int newX) {

x = newX;

}

}

class AnInteger {

static int x;

public int x() {

return x;

}

public void setX(int newX) {

x = newX;

}

}

Class and Instance Members (Continued)

class AnInteger {

int x;

static public int x() {

return x;

}

static public void setX(int newX){

x = newX;

}

}

AnInteger myX = new AnInteger();

AnInteger yourX = new AnInteger();

myX.setX(1);

yourX.x = 2;

System.out.println(“myX = “ + myX.x());

System.out.println(“yourX = “ + yourX.x());


Garbage collection
Garbage Collection

  • Unreferenced Objects are Garbage Collected Automatically

  • Memory is Freed for Later Reuse

  • Garbage Collection runs in a Low Priority Thread, either Synchronously or Asynchronously

  • The finalize() Method is Inherited from Object and can be Overridden to Liberate Resources


Inheritance in java
Inheritance in Java

  • Basic Definitions and Concepts

    • Generalization vs. Specialization

    • Subclass vs. Superclass

  • Acquisition Rules

    • What Does Superclass Pass to Subclass?

    • What Does Subclass Inherit from Superclass?

    • What is Visible within Packages?

    • Overriding vs. Overloading?

  • Role of Public, Final, and Abstract Classes

  • Java Interfaces for Design-Level Multiple Inheritance and Quasi Generics


Inheritance terms and concepts
Inheritance - Terms and Concepts

  • Every Class in Java is Derived from the Object Class

  • Java Classes can be Organized into Hierarchies Using the extends Keyword

  • Establishing Superclass/Subclass Relationships Between the Classes in Application

  • A Superclass Contains Members Common to Its Subclasses - Generalization

  • Subclasses Contain Members Different from Shared Superclass - Specialization

  • Only Single Inheritance is Supported in Java at Implementation Level!


Subclass superclass
Subclass & Superclass

  • Subclass

    • Subclass is a Class that Extends Another Class

    • Inherits State and Behavior from all of its Ancestors

    • Subclass can use the Inherited Member Variables and Functions or hide the Inherited Member Variables and Override the Inherited Member Functions

  • Superclass

    • Superclass is a Class’s Direct Ancestor


A superclass in java
A Superclass in Java

  • A Supermarket Item

  • Keywords must be Utilized for Each Attribute or Method Declaration

class Item {

private String UPC, Name;

private int Quantity;

private double RetailCost;

protected double WholeCost;

public Item() { ... };

public void finalize() { ... };

public boolean Modify_Inventory(int Delta){...};

public int Get_InStock_Amt()

{return Quantity;};

};


Inheritance defining subclasses in java
Inheritance - Defining Subclasses in Java

Item

/ \

DeliItem ProduceItem

|

SaladItem

class DeliItem extends Item { ... };

class SaladItem extends DeliItem { ... };

class ProduceItem extends Item { ... };


Members inherited by a subclass
Members Inherited By a Subclass

  • Subclass Inherits all Public/Protected Members of a Superclass

    • DeliItem Inherits Public/Protected from Item

  • Subclass Inherits all Package Members of Classes in the same Package as the Subclass

  • All superclass Members can be Declared with no Access Specification, if Subclass is in the Same Package as the Superclass


Members not inherited by a subclass
Members Not Inherited By A Subclass

  • Subclass does not Inherit Private Members of a Superclass

    • DeliItem doesn’t Inherit Private from Item

  • Subclasses do not Inherit a Superclass’s Member if the Subclass Declares a Member with Same Name

    • Member Variables - Subclass Hides the Member Variable of the Superclass

    • Member Methods - Subclass Overrides the one in the Superclass


Hiding member variables and overriding member methods
Hiding Member Variables and Overriding Member Methods

class parentClass {

boolean state;

void setState() {

state = true;

}

}

class childClass extends parentClass {

boolean state;

void setState() {

state = false;

super.setState();

System.out.println(state);

System.out.println(super.state)

}

}


Overriding member methods
Overriding Member Methods

  • Subclasses CANNOT Override Methods that are Declared to be Final in the Superclass

  • Subclasses MUST Override Methods that are Declared as Abstract in the Superclass

  • Subclasses MUST be Declared as Abstract if they do not Override Abstract Methods from the Superclass


Methods inherited from object class
Methods Inherited From Object Class

  • The Java “Object” Class Defines Basic State and Behavior of all Classes and Their Instances

  • User Defined Classes can Override these Methods:

    • clone

    • equals

    • finalize

    • toString

    • hashCode

  • User Defined Classes Cannot Override:

    • getClass

    • notify

    • notifyAll

    • wait


Public final and abstract classes
Public, Final, and Abstract Classes

  • Public Classes

    • Within Package, public Classes Become Visible to Outside World

    • Public Members are Exported

  • Final Classes

    • Prohibits Subclassing for Security

    • Final Class Prevents Access of Protected Members via Subclassing

    • Not Supported in C++/Ada95

  • Abstract Classes

    • Can't be Instantiated

    • No Implementations for Abstract Methods


Final classes and the final keyword
Final Classes and the “Final” Keyword

  • A Class is Declared as Final - the Class Cannot be Subclassed.

    • For Security

    • For Design

  • A Method is Declared as Final in a Class - any Subclass Cannot Override that Method

  • A Variable is Declared as Final - the Variable is a Constant and it Cannot be Changed


Abstract classes and methods
Abstract Classes And Methods

  • Abstract Classes

    • Cannot be Instantiated

    • Can only be Subclassed

    • Keyword “abstract” before Keyword “class” is used to Define an Abstract Class

    • Example of an Abstract Class is Number in the java.lang Package

  • Abstract Methods

    • Abstract Classes may contain Abstract Methods

    • This allows an Abstract Class to Provide all its Subclasses with the Method Declarations for all the Methods


A sample abstract class
A Sample Abstract Class

abstract class Item {

protected String UPC, Name;

protected int Quantity;

protected double RetailCost, WholeCost;

public Item() { ... };

abstract public void finalize();

abstract public boolean

Modify_Inventory(int Delta);

public int Get_InStock_Amt() {...};

public double Compute_Item_Profit() {...};

protected boolean

Modify_WholeSale(double NewPrice);{...};

};


Another abstract class and methods
Another Abstract Class and Methods

abstract class GraphicsObject{

int x, y;

void moveTo(int x1,y1) { . . . . . }

abstract void draw();

}

class Circle extends GraphicsObject{

void draw() { . . . . . }

}

class Rectangle extends GraphicsObject{

void draw() { . . . . . }


Interfaces in java
Interfaces in Java

  • Design-Level Multiple Inheritance

  • Java Interface

    • Set of Methods (no Implementations)

    • Set (Possibly Empty) of Constant Values

  • Interfaces Utilized Extensively Throughout Java APIs to Acquire and Pass on Functionality

    • Threads in Java - Multiple Concurrent Tasks

    • Subclassing from Thread Class (java.lang API)

    • Implementing an Interface of Runnable Class


A sample interface in java
A Sample Interface in Java

Teaching

Student Employee

/ \ |

UnderGrad Graduate Faculty

interface Teaching {

int NUMSTUDENTS = 25;

void recordgrade(Undergrad u, int score);

void advise(Undergrad u);

... etc ...

}

class Graduate extends Student implements Teaching{

...}

class Faculty extends Employee implements Teaching{

...}

recordgrade() Different for Graduate & Faculty


Quasi generics in java
Quasi Generics in Java

class Set implements Coll{

void add(Object obj){

... }

void delete(Object obj){

... }

}

interface Coll {

int MAXIMUM = 500;

void add(Object obj);

void delete(Object obj);

Object find(Object obj);

int currentCount();

}

class Queue implements Coll{

void add(Object obj){

... }

void delete(Object obj){

... }

}


Polymorphism and object serialization in java
Polymorphism and Object Serialization in Java

  • Polymorphism

    • Polymorphism via Dispatching Allows a Runtime or Dynamic Choice of the Method to be Called based on the Class Type of the Invoking Instance

    • Promotes Reuse and Evolution of Code

    • Polymorphism/Dispatching Incurs Cost or Overhead at both Compile and Runtime!

  • Serialization

    • Conversion of Object to Format that Facilitates Storage to File or Transfer Across Network

    • Process Controlled via API with Minimal Interaction by Software Engineer


Polymorphism
Polymorphism

  • Substitutability

    • Whenever Value of a Certain Type is Expected, a Subtype can also be Provided

    • In Context of Inheritance, All Subclasses can be Treated as Common Root Class

    • Simplifies Code and Facilitates Reuse

  • Static Type

    • Type Defined in the Variable Declaration

  • Dynamic Type

    • Type of the Actual Value held by the Variable at Runtime


Polymorphism1
Polymorphism

  • A Variable is Polymorphic Whenever it may have Different Static and Dynamic Types

    • Static Variable I1 Defined with Type Item

    • Dynamic Variable Access Allows I1.Print() to be Invoked on DeliItem, ProduceItem, etc., Instances

  • Problems:

    • Reverse Polymorphism: Can we get the Subtype Variable Back After Assigning its Value to a Supertype?

    • Method Binding: When Invoking a Method on a Variable, should it be Selected According to its Static or Dynamic Type?


An example
An Example

  • We have a class Ball, and two subclasses WhiteBall and BlackBall

  • The SelectOne() method gets a WhiteBall and a BlackBall as arguments and returns one of them selected randomly

  • Questions:

    • What is SelectOne()’s return type?

    • How can we know which ball was returned?

SelectOne

?


Dynamic binding and casting

public class Ball {

public String id = new String("I'm a ball");

public String GetId() {

return id;

}

}

public class WhiteBall extends Ball {

public String id = new String("I'm white");

public String GetId() {

return id;

}

public void OnlyWhite() {

System.out.println("Yes, I'm white");

}

}

public class BlackBall extends Ball {

public String id = new String("I'm black");

public String GetId() {

return id;

}

public void OnlyBlack() {

System.out.println("Yes, I'm black");

}

}

class balls {

public static void main(String[] args) {

WhiteBall wb = new WhiteBall();

BlackBall bb = new BlackBall();

Ball b = SelectOne(wb, bb);

System.out.println(b.GetId());

System.out.println(b.id);

if (b instanceof WhiteBall) {

wb = (WhiteBall)b;

wb.OnlyWhite();

} else {

bb = (BlackBall)b;

bb.OnlyBlack();

}

}

public static Ball SelectOne(WhiteBall w, BlackBall b) {

if (Math.random() > 0.5)

return w;

else

return b;

}

}

Dynamic Binding and Casting

The static type of b is Ball, but its

dynamic type is either WhiteBall

or BlackBall.

What is going to be printed?


Class student superclass maintains student information

public class Student

{ // protected used to facilitate inheritance

protected String name, SSN;

protected float gpa;

// constructor used to initialize object

public Student(String n, String ssn,float g)

{

name = n;

SSN = ssn;

gpa = g;

}

public String getName()

{ return name; }

public float getGpa()

{ return gpa; }

public String getSSN()

{ return SSN; }

// diplay student information

public void print()

{

System.out.println("Student name: " + name);

System.out.println(" SSN: " + SSN);

System.out.println(" gpa: " + gpa);

}

}

Class Student (Superclass) - Maintains Student Information


Class grad
Class Grad

public class Grad extends Student

{

private String thesis;

public Grad(String name, String ssn, float gpa, String t)

{

// call parent's constructor

super(name, ssn, gpa);

thesis = t;

}

public String getThesis()

{ return thesis; }

public void print()

{

super.print();

System.out.println(" thesis: " + thesis);

}

}


Class undergrad
Class Undergrad

public class Undergrad extends Student {

private String advisor;

private String major;

public Undergrad(String name, String ssn, float gpa, String adv, String maj){

super(name, ssn, gpa);

advisor = adv;

major = maj;

}

public String getAdvisor()

{ return advisor; }

public String getMajor()

{ return major; }

public void print() {

super.print();

System.out.println(" advisor: " + advisor);

System.out.println(" major: " + major);

}

}


Class studentdb

import java.util.Vector;

public class StudentDB{

private Vector stuList;

// constructor

public StudentDB(int size){

// allocate memory for vector

stuList = new Vector(size);

}

// returns number of students stored

public int numOfStudents()

{ return (stuList.size()); }

public void insert(Student s)

{ stuList.addElement(s); }

// search for student by name

public Student findByName(String name){

Student stu = null; // temp student

boolean found = false;

int count = 0;

int DBSize = stuList.size();

while ((count < DBSize)||(found == false)){

stu = (Student) stuList.elementAt(count);

if (stu.getName().equals(name))

found = true;

count++;

}

return stu;

}

Class StudentDB


Class studentdb continued

public Student remove(String name)

{

Student stu = null; // temp student

boolean found = false;

int count = 0;

int DBSize = stuList.size();

while ((count < DBSize) || (found == false)){

stu = (Student) stuList.elementAt(count);

if (stu.getName().equals(name))

found = true;

count++;

}

if (found == true)

stuList.removeElementAt(count - 1);

return stu;

}

public void displayAll()

{

int DBSize = stuList.size();

for (int i = 0; i < DBSize; i++)

{

Student stu = (Student) stuList.elementAt(i);

stu.print();

System.out.println();

}

}

}

Class StudentDB (Continued)


Class maininterface

public class MainInterface

{

private StudentDB db;

public static void main(String[] args) {

MainInterface studentInt = new MainInterface();

studentInt.displayMenu();

}

// constructor

public MainInterface() {

db = new StudentDB(5);

}

public void displayMenu(){

int option = 0;

System.out.println("\n 1. Insert ");

System.out.println(" 2. Delete ");

System.out.println(" 3. Search ");

System.out.println(" 4. Display ");

System.out.println(" 5. Exit \n");

option = Console.readInt("Enter your choice: ");

while (option > 0 && option < 5) {

processOption(option);

System.out.println("\n 1. Insert ");

System.out.println(" 2. Delete");

System.out.println(" 3. Search ");

System.out.println(" 4. Display ");

System.out.println(" 5. Exit \n");

option = Console.readInt("Enter your choice: "); } }

Class MainInterface


Class maininterface continued

public void processOption(int option)

{

String name, SSN;

float gpa;

switch (option){

case 1:

int type = Console.readInt("1. Grad or 2. Undergrad? ");

name = Console.readString(“Name: ");

SSN = Console.readString(“SSN: ");

gpa = (float) Console.readDouble("gpa: ");

if (type == 1){

String thesis = Console.readString("Enter thesis title:");

Student g = new Grad(name, SSN, gpa, thesis);

db.insert(g);

}

Class MainInterface (Continued)


Class maininterface continued1

else{

String advisor = Console.readString("Enter advisor:");

String major = Console.readString("Enter major: ");

Student u = new Undergrad(name, SSN, gpa, advisor,

major);

db.insert(u);

}

break;

case 2:

name = Console.readString(”Name");

Student s = db.remove(name);

s.print();

break;

Class MainInterface (Continued)


Class maininterface continued2
Class MainInterface (Continued)

case 3:

name = Console.readString("Enter name: ");

Student stu = db.findByName(name);

System.out.println();

stu.print();

break;

case 4:

System.out.println();

db.displayAll();

}

}

}


Object serialization
Object Serialization

  • Object Serialization is the Process of Reading and Writing Objects

    • Bi-directional Process of Write (Save in Serialized form) and Read (Reconstruct from Serialized form)

  • ObjectInputStream and ObjectOutputStream are used for Reading and Writing Objects

  • Used in:

    • Remote Method Invocation (RMI)

    • Lightweight Persistence - Archival for Use in a Later Invocation of a Program

    • Exchange of Information Across Network

    • Agent-Based/Aglet Computing


Using object serialization
Using Object Serialization

  • Straightforward Process in Java

  • Serialize Objects by ...

    • Writing Objects to an ObjectOutputStream

  • Deserialize Objects by ...

    • Reading Objects using ObjectInputStream

  • Design/Develop Classes that Promote the Serialization/Deserialization of Instances

  • Serialize/Deserialize at Topmost Level:

    • Automatically Includes Component Instances, Set and Collection Instances, User-Defined Class Instances, etc.

    • Whatever is Declared with Class and Active within Instance


Writing to an objectoutputstream
Writing to an ObjectOutputStream

  • The Following Code Segment Serializes the Date Object

    FileOutputStream out = new FileOutputStream("theTime");

    ObjectOutputStream s = new ObjectOutputStream(out);

    s.writeObject("Today");

    s.writeObject(new Date());

    s.flush();

  • Serializes the Object to a File named “theTime”


Reading from an objectinputstream
Reading From an ObjectInputStream

  • The Following Code Segment Reconstructs by Deserializing the Date Object:

    FileInputStream in = new FileInputStream("theTime");

    ObjectInputStream s = new ObjectInputStream(in);

    String today = (String)s.readObject();

    Date date = (Date)s.readObject();

  • Object and its Components (if any) are Read from the File “theTime”

  • If Multiple Independent Objects were Written, Objects must be Read in the Same Order

  • Return Value from readObject has to be Cast to a Specific Type


Utilizing object serialization
Utilizing Object Serialization

  • Serialization/Deserialization Occurs via the Implementation of the Java Serializable Interface

  • An Object is Serializable only if its Class Implements the Serializable Interface

    • Serialization Utilizes Exception Handling

    • For Example, writeObject Method Throws a NotSerializableException if the given Object is not serializable

  • Serializable is an Empty Interface

    • Does not Contain Any Method Declarations

    • Identifies Classes whose Objects are Serializable


Implementing the serializable interface
Implementing the Serializable Interface

  • The Serializable Interface

    • public interface Serializable { // there's nothing in here!};

  • To make Instances of a Vlass serializable, add the Implements Serializable to Class Defenition

    • public class MySerializableClass implements Serializable { … }

    • User does not have to Write any Methods

  • Serialization of Objects are Handled by the defaultWriteObject Method of the ObjectOutputStream


Defaultwriteobject method
defaultWriteObject Method

  • The defaultWriteObject Method is Defined in ObjectOutputStream Class

  • defaultWriteObject Writes all Necessary Details to Reconstruct an Instance of the Class

    • Class of the Object

    • Class Signature

    • Values of Non-Transient and Non-Static Members Including References to Other Contained Objects

    • In Turn, Contained Objects, their Classes, Signatures, Values, etc., are also Written

    • Process Continues in a Logically Recursive Fashion


ad