Jump start java
Download
1 / 78

Jump Start : Java - PowerPoint PPT Presentation


  • 265 Views
  • Uploaded on

Jump Start : Java. B.Ramamurthy Copyright 1998 CSE Department. Topics for Discussion. OO Design Principles Java Virtual Machine Java Application Structure Class and objects Methods and Variables Access/Visibility Modifiers Debugging Inheritance

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 'Jump Start : Java' - Jeffrey


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
Jump start java l.jpg

Jump Start : Java

B.Ramamurthy

Copyright 1998

CSE Department

BR


Topics for discussion l.jpg
Topics for Discussion

  • OO Design Principles

  • Java Virtual Machine

  • Java Application Structure

  • Class and objects

  • Methods and Variables

  • Access/Visibility Modifiers

  • Debugging

  • Inheritance

  • Abstract classes, interfaces and implementation

  • JDK Event Model

  • Applets and Appletviewer

  • Summary

BR


Object oriented principles l.jpg
Object-Oriented Principles

OOP

Polymorphism

-- Many forms of

same function

-- Abstract Methods

-- Abstract Classes

Inheritance

-- Hierarchy

-- Reusability

-- Extensibility

-- Expressive power

-- Reflects many

real-world problems

Encapsulation

(class)

-- Information Hiding

-- Interface and

Implementations

-- Standardization

-- Access Control mechanisms

(private /public etc.)

BR


Conventional compiled languages l.jpg

Mac Hardware

Mac Compiler

Mac Compiler

C++source

PC Hardware

C++source

PC Compiler

PC Hardware

C++source

Sun Compiler

Conventional Compiled Languages

BR


Java virtual machine l.jpg
Java Virtual Machine

JVM

Java compiler :javac

Mac Hardware

Byte code

Mac Compiler

C++source

Mac interpreter

JVM

PC Hardware

Byte code

C++source

PC Interpreter

JVM

PC Hardware

Byte code

C++source

Sun Interpreter

BR


Run anywhere capability l.jpg

On any machine when you compile Java source code using javac byte code equivalent to the source is generated.

Byte code is machine-independent. This enables the “run-anywhere” capability.

You invoke java command which will feed the byte code to the machine-dependent interpreter.

“Run-anywhere” Capability

BR


Java application program interface java api l.jpg
Java Application Program Interface (Java API)

(JAVA API)

Package of related

classes : java.awt

Random

java.util

Date

Dictionary

Java.io, java.beans,..

Etc..

package

class

BR


Java api a simplistic view l.jpg
Java API : A Simplistic View

API

packages

classes

methods and data declarations

BR


Java api classes l.jpg
Java API Classes

  • Unlike many other languages, you will referring to the classes in the API.

  • Where is the API?

  • Packages are in:

    /util/lang/jdk1.1.6/src/java

  • “cd” to any package of interest:

    awt, lang, io, graphics…..

  • You will see the methods and data defined in the classes in the package.

BR


Types of programs l.jpg

Java is fully object-oriented.

Every “function” has to be attached to a class.

You will mainly deal with three types of programs:

class: methods and data (variables + constants) describing a collection (type) of object

application: class that has a main method: represents a our regular program

applet: class that is meant for execution using a appletviewer/browser

Types of Programs

BR


Problem solving using java l.jpg
Problem Solving Using Java

OO Design and Progamming in Java

Write an

applet

class

Identify classes needed

Write an

application

class

Reuse API

classes

Reuse

your classes

Design new

classes

Create and use objects

BR


What is an object l.jpg
What is an Object?

  • Object-oriented programming supports the view that programs are composed of objects that interact with one another.

  • How would you describe an object?

  • Using its characteristics (has a ----?) and its behaviors (can do ----?)

  • Object must have unique identity (name) : Basketball, Blue ball

  • Consider a ball:

    • Color and diameter are characteristics (Data Declarations)

    • throw, bounce, roll are behaviors (Methods)

BR


Classes are blueprints l.jpg
Classes are Blueprints

  • A class defines the general nature of a collection of objects of the same type.

  • The process creating an object from a class is called instantiation.

  • Every object is an instance of a particular class.

  • There can be many instances of objects from the same class possible with different values for data.

BR


Example l.jpg
Example

objects

Object

References

redRose

class Rose

blueRose

class

BR


Instantiation examples l.jpg
Instantiation : Examples

  • class FordCar ---- defines a class name FordCar

  • FordCar windstar; ---- defines a Object reference windStar

  • windstar = new FordCar(); ---- instantiates a windstar Object

  • class HousePlan1 { color….

  • HousePlan1 blueHouse;

  • blueHouse = new HousePlan1(BLUE);

  • HousePlan1 greenHouse = new HousePlan1(GREEN);

BR


Operator new and dot l.jpg
Operator new and “dot”

  • new operator creates a object and returns a reference to that object.

  • After an object has been instantiated, you can use dot operator to access its methods and data declarations (if you have access permissions).

  • EX: redRose.bloom(); greenHouse.color

BR


Elements of a class l.jpg
Elements of a Class

class

data declarations (variables,

constants)

methods

header

body

header

statements

modifiers,

type, name

variables,

constants

parameters

repetition

others

selection

assignment

BR


Class structure l.jpg
Class Structure

class

variables

constants

methods

BR


Defining classes l.jpg
Defining Classes

  • Syntax:

  • class class_name {

  • data-declarations

  • constructors

  • methods }

  • Constructors are special methods used for instantiating (or creating) objects from a class.

  • Data declarations are implemented using variable and constant declarations.

BR


Naming convention l.jpg

Constants: All characters in uppercase, words in the identifier separated by underscore: EX: MAX_NUM

Variables, objects, methods: First word all lowercase, subsequent words start with uppercase. EX: nextInt, myPen, readInt()

Classes: Start with an uppercase letter. EX: Tree, Car, System , Math

Naming Convention

BR


A complete example l.jpg
A complete example identifier separated by underscore: EX: MAX_NUM

  • Problem Statement: You have been hired to assist in an secret encryption project. In this project each message (string) sent out is attached to a randomly generated secret code (integer) between 1 and 999. Design and develop an application program in Java to carry out this project.

BR


Identify objects l.jpg
Identify Objects identifier separated by underscore: EX: MAX_NUM

  • There are two central objects:

    • Message

    • Secret code

  • Is there any class predefined in JAVA API that can be associated with these objects? Yes ,

    • “string” of java.lang and “Random” of java.util

BR


The random class l.jpg
The Random class identifier separated by underscore: EX: MAX_NUM

  • Random class is defined in java.util package.

  • nextInt() method of Random class returns an integer between 0 and MAXINT of the system.

BR


Design l.jpg

Class Random identifier separated by underscore: EX: MAX_NUM

Class String

An instance of Random

number generator

An instance of string

Input and fill up message.

Generate Random integer

Attach (concatenate)

Design

Output combined message.

For implementation see /projects/bina/java/secretMsg.java

BR


Debugging and testing l.jpg

Compile-time Errors : Usually typos or syntax errors identifier separated by underscore: EX: MAX_NUM

Run-time Errors : Occurs during execution. Example: divide by zero .

Logic Errors: Software will compile and execute with no problem, but will not produce expected results. (Solution: testing and correction)

See /projects/bina/java/Peets directory for an exercise.

Debugging and Testing

BR


Class components l.jpg
Class Components identifier separated by underscore: EX: MAX_NUM

  • Class name (starts with uppercase), constants, instance variables, constructors definitions and method definitions.

  • Constants:

    public final static double PI = 3.14;

  • Variables:

    private double bonus;

    public string name;

BR


Method invocation call l.jpg
Method Invocation/Call identifier separated by underscore: EX: MAX_NUM

  • Syntax:

    method_name (values);

    object_name.method_name(values);

    classname.method_name(values);

    Examples:

    computeSum(); // call to method from within the class where it is located

    YourRose.paintIt(Red);

    Math.abs(X);

BR


Defining methods l.jpg
Defining Methods identifier separated by underscore: EX: MAX_NUM

  • A method is group of (related) statements that carry out a specified function.

  • A method is associated with a particular class and it specifies a behavior or functionality of the class.

  • A method definition specifies the code to be executed when the method is invoked/activated/called.

BR


Method definition syntax l.jpg
Method Definition : Syntax identifier separated by underscore: EX: MAX_NUM

visibilityreturn_type method_name

(parameter_list)

{

statements

}

BR


Return type l.jpg
Return Type identifier separated by underscore: EX: MAX_NUM

  • can be void, type or class identifier

  • void indicates that the method called to perform an action in a self-standing way: Example: println

  • type or class specify the value returned using a return statement inside the method.

BR


Return statement l.jpg
Return Statement identifier separated by underscore: EX: MAX_NUM

  • Syntax of return statement:

    return; // for void methods

    return expression; // for type or class return value

    // the expression type and return type should be same

BR


Parameter list l.jpg
Parameter List identifier separated by underscore: EX: MAX_NUM

  • Parameter list specified in method header provides a mechanism for sending information to a method.

  • It is powerful mechanism for specializing an object.

  • The parameter list that appears in the header of a method

    • specifies the type and name of each parameter and

    • is called formal parameter list.

  • The corresponding parameter list in the method invocation is called an actual parameter list.

BR


Parameter list syntax l.jpg
Parameter list : Syntax identifier separated by underscore: EX: MAX_NUM

  • Formal parameter list: This is like molds or templates

    (parm_type parm_name, parm_type parm_name, ....)

  • Actual parameter list: This is like material that fit into the mold or template specified in the formal list:

    (expression, expression....)

BR


Method definition review l.jpg
Method Definition : review identifier separated by underscore: EX: MAX_NUM

definition

header

body

Visibility

modifiers

parameter list

return type

Name

{ statements }

BR


Method definition example l.jpg
Method Definition : Example identifier separated by underscore: EX: MAX_NUM

  • Write a method that computes and returns the perimeter of a rectangle class.

  • Analysis:

    • Send to the method: Length and Width

    • Compute inside the method: Perimeter

    • Return from the method: Perimeter

BR


Example contd l.jpg
...Example (contd.) identifier separated by underscore: EX: MAX_NUM

public int Perimeter (int Length, int Width)

{

int Temp; // local temporary variable

Temp = 2 * (Length + Width); // compute perimeter

return Temp; // return computed value

}

BR


What happens when a method is called l.jpg
What happens when a method is called? identifier separated by underscore: EX: MAX_NUM

  • Control is transferred to the method called and execution continues inside the method.

  • Control is transferred back to the caller when a return statement is executed inside the method.

BR


Method invocation semantics l.jpg
Method Invocation : semantics identifier separated by underscore: EX: MAX_NUM

Operating

System

1. OS to main method

2. Main method execution

3. Invoke Area

4. Transfer control to Area

5. Execute Area method

6. Return control back to

main method

7. Resume executing main

8. Exit to OS

8

1

2

Main method

Rect.Area(….)

3

7

4

8

Area

method

5

6

BR


Constructors l.jpg
Constructors identifier separated by underscore: EX: MAX_NUM

  • A Constructor is used to create or instantiate an object from the class.

  • Constructor is a special method:

    • It has the same name as the class.

    • It has no return type or return statement.

  • Typically a class has more than one constructor: a default constructor which has no parameters, and other constructors with parameters.

BR


Constructors contd l.jpg
Constructors (contd.) identifier separated by underscore: EX: MAX_NUM

  • You don’t have to define a constructor if you need only a default constructor.

  • When you want initializing constructors :

    1. you must include a default constructor in this case.

    2. You will use initializing constructors when you want the object to start with a specific initial state rather than as default state.

    3. Example: Car myCar(Red); // initializing constructor for Car class with color as parameter

BR


Visibility modifiers l.jpg
Visibility Modifiers identifier separated by underscore: EX: MAX_NUM

type

Method/variable name

public

protected

“nothing”

DEFAULT

private

static

“nothing”

DEFAULT

To indicate

class method/

variable

To indicate

object

method/

variable

BR


Modifiers contd l.jpg

private : available only within class identifier separated by underscore: EX: MAX_NUM

“nothing” specified : DEFAULT: within class and within package

protected : within inherited hierarchy (only to sub classes)

public : available to any class.

..Modifiers (contd.)

BR


Classpath l.jpg

Many times classes needed are available in a repository other than the Java API.

Set the CLASSPATH environment variable to point to such repositories. One such is located in /projects/bina/cs114/structures

setenv CLASSPATH

.:/util/lang/jdk1.1.6/lib/classes.zip:/projects/bina/cs114/structures

(all in a continuous line)

CLASSPATH

BR


Classpath44 l.jpg
CLASSPATH other than the Java API.

  • Now you may refer to any one of the classes in the structures directory.

  • The source code is available in

  • /projects/bina/cs114/sources

  • Checkout ReadStream and Keyboard classes for nice inputs.

BR


Inheritance l.jpg
Inheritance other than the Java API.

  • Inheritance is the act of deriving a new class from an existing one.

  • A primary purpose of inheritance is to reuse existing software.

  • Original class used to derive a new class is called “super” class and the derived class is called “sub” class.

  • Inheritance represents “is a” relationship between the superclass and the subclass.

BR


Syntax l.jpg
Syntax other than the Java API.

class subclass extends superclass {

class definition

}

Example:

class Windstar extends FordCar // meaning it inherits from class Fordcar{ ....}

Windstar myCar();

In this example, FordCar is the super-class and Windstar is a sub-class and myCar is an object Windstar class.

BR


Representing the relationship l.jpg
Representing the Relationship other than the Java API.

BankClass

has a

has a

has a

Account [ ]

MortgageSVC

BrokerageSVC

is a

is a

Savings

Checking

is a : use inheritance

has a : use composition, or membership

BR


Modifers l.jpg
Modifers other than the Java API.

  • Visibility modifiers: private, public, protected

  • Protected modifier is used when the entity needs to be available to the subclass but not to the public.

BR


Example words l.jpg
Example : Words other than the Java API.

Main class

Book class

Super class

Uses

is a

Dictionary Class

subclass

BR


Example school l.jpg
Example : School other than the Java API.

Student

Main class

uses

Grad Student

BR


Abstract class abc and methods l.jpg
Abstract Class (ABC) and methods other than the Java API.

  • An abstract class or method is defined using “abstract” modifier.

  • An abstract method has no definition in the super class.

  • ABC cannot be instantiated.

  • Sole purpose of ABC is to provide an appropriate super class from which classed may inherit.

  • Classes from which objects can be instantiated are called concrete classes.

BR


Example52 l.jpg
Example other than the Java API.

Food

Abstract super class

Pizza

Hamburger

HotDog

subclasses

BR


Interface l.jpg

An other than the Java API.abstract method is one that does not have a definition within the class. Only the prototype is present.

An interface is collection of constants and abstract methods.

Syntax

interface interface_name {

constant -declarations;

abstract methods;

}

Interface

BR


Example54 l.jpg

interface EPA { other than the Java API.

bool emissionControl();

bool pollutionControl();

}

class NYepa implements EPA {

bool emissionControl () {

details/semantics /statements how to implement it }

class CAepa implements EPA {

bool emissionControl () {….

// different details on implementation….}

Example

BR


Inheritance and interfaces l.jpg

In Java class may inherit (extend) from only one class. (C++ allows multiple inheritance).

But a Java class may implement many interfaces.

For example,

public class Scribble extends Applet implements MouseListner, MouseMotionListner {

Inheritance and Interfaces

BR


Types of programs56 l.jpg
Types of Programs allows multiple inheritance).

  • Console programs:

    • Control-driven: You start the program and the program code determines the sequence of events.

    • Mostly the actions are predetermined.

  • Windows-based programs:

    • Event-driven: The operation of the program depends on what you do with the controls presented (usually by the GUI)

    • Selecting menu items, pressing buttons, dialog interaction cause actions within the program.

BR


Events l.jpg
Events allows multiple inheritance).

1. Actions such as clicking a button, moving a mouse, are recognized and identified by the operating systems(OS).

2. For each action, OS determines which of the many currently running programs should receive the signal (of the action)

3. The signals that the application receives from the OS as result of the actions are called events.

BR


Event generation l.jpg
Event Generation allows multiple inheritance).

User Interface

Other

event

sources

Mouse actions, Keystrokes

Operating Systems

JAVA API

Events

Methods and handlers

Methods and handlers

Application 1

Application 2

BR


Event handlers l.jpg

An application responds to the events by executing particular code meant for each type of event.

Not all events need to be handled by an application. For example, a drawing application may be interested in handling only mouse movements.

As a designer of an event-driven application you will write methods to handle the relevant events.

Event Handlers

BR


Event handling process l.jpg
Event Handling Process particular code meant for each type of event.

  • Source of an event is modeled as an object. Ex: button click’s object is a button

  • Type of the event: ActionEvent, WindowEvent, MouseEvent etc. Ex: An ActionEvent object is passed to the application that contains information about the action.

  • Target of an event: Listener object of the event. Passing the event to a listener means calling the particular method of the listener object.

BR


Java event model l.jpg
Java Event Model particular code meant for each type of event.

  • Java event model has changed quite significantly between JDK1.0 and JDK 1.1.

  • Many Web Browsers still use JDK1.0.

  • JDK1.0 event model is good for understanding event-driven programming and for simple applications but does not scale well for large applications.

  • It is impossible to take a in-depth look at any one. But we will learn enough to use some basic features.

BR


Java class hierarchy l.jpg
Java Class Hierarchy particular code meant for each type of event.

java.lang

Object

java.awt

Component

“others”

Label

TextComponent

Button

Container

java.applet package

Window

Panel

Applet

Dialog

Frame

BR


Jdk1 1 event model system support l.jpg
JDK1.1 Event Model : System support particular code meant for each type of event.

Many Event classes

Low-level classes

Semantic classes

FocusEvent

MouseEvent

Etc.

Etc.

ActionEvent

TextEvent

: methods

Listener Interfaces

BR


Jdk1 1 event model application support l.jpg

Instantiate particular code meant for each type of event. objects from component classes such as buttons and checkboxes which will serve as source of the events.

Implement listener interfaces.

Define methods to handle events of interest.

Example: /projects/bina/java/Doodle.java

JDK1.1 Event Model : Application Support

BR


Implementing listeners l.jpg
Implementing Listeners particular code meant for each type of event.

  • An application (class) becomes a listener when it implements the listener interface.

  • Java 1.1 event model provides a variety of listeners.

  • EX:

    • If an application is interested in button click, it will have to implement ActionListener interface.

    • actionPerformed() method of the ActionListener will have be implemented by the application.

    • When the button click event occurs, actionPerformed() method will be called with event object as argument.

BR


Example doodle java l.jpg
Example: Doodle.java particular code meant for each type of event.

1. Include “implements” at the header of the class : This application uses MouseListener and MouseMotionListener interfaces

2. Invoke “ methods” to add/activate required listeners. Here we have three:

a) mouse click

b) mouse motion

c) window close

3. Set up board : use paint() and fillRect() methods.

BR


Example contd67 l.jpg
Example (contd.) particular code meant for each type of event.

4. Implement all the methods (even if it is empty) of the interface (why?)

5. This application needs only MousePressed and MouseReleased for line color selection and MouseDragged for drawing lines.

6. Finally an adapter class that handles window closing.

BR


Applet l.jpg
Applet particular code meant for each type of event.

  • An applet is a Java program that operates within a browser and hence can appear in a web page.

  • It can be fetched from a remote computer and run on the local computer.

  • Applet’s enabling technologies:

    • Java Virtual Machine (JVM)

    • Interpretation rather than compilation

BR


Requirements l.jpg
Requirements particular code meant for each type of event.

  • Besides the classes, an applet requires a .html file and a tool for viewing the applet (Ex: appletviewer of JDK)

  • An applet extends Applet class of java.applet package.

    import java.applet.Applet;

  • An applet should have at least an init() or a paint() method (just as an application should have main() method)

BR


Applet class l.jpg
Applet Class particular code meant for each type of event.

  • Applet class has four important methods:

    init()

    start()

    stop()

    destroy()

    Besides these paint() method of component class is commonly used for drawing graphics in an applet window.

BR


Applet runtime structure l.jpg

Applet particular code meant for each type of event.

file

.java

Applet Runtime Structure

html

file

.html

includes

javac

appletviewer

Java runtime

JVM

Applet

file

.class

BR


Example 1 using only paint l.jpg

//file : MyApplet.java particular code meant for each type of event.

import java.applet.Applet; // step 1

import java.awt.Graphics;

public class MyApplet extends Applet //step 2

{

public void paint( Graphics g) // step 3

{ g.drawString(“To climb a ladder”, 20, 90); }

}

Example 1: Using only paint()

BR


Example 1 interpretation l.jpg
Example 1: interpretation particular code meant for each type of event.

step 1: import Applet class

step 2: inherit from Applet class

step 3: Overload /redefine/customize paint() method

BR


Html file l.jpg
html file particular code meant for each type of event.

1. Create a html file:

<APPLET code=“MyApplet.class” width=300 height=200>

<\APPLET>

2. Save as MyApplet.html

3. To create class: javac MyApplet.java

4. To execute: appletviewer MyApplet.html

BR


Example 1 execution semantics l.jpg
Example 1: execution semantics particular code meant for each type of event.

Java run-time system will look for init(), then start() methods.

Default definitions of init() and start() are executed.

Then user-applet-defined paint() method is executed.

Rest of the control follows default methods.

BR


More on applets l.jpg
More on Applets particular code meant for each type of event.

1. main() is replaced by init() or paint() methods

2. An applet cannot access local programs or files

3. Very useful in creation of active/dynamic web pages

4. Implements “behavior streaming”

5. Popular component of Java language.

BR


On line information l.jpg
On-line Information particular code meant for each type of event.

file:/util/lang/jdk1.1.6/api/API_users_guide.html

has user’s manual for Java API

/util/lang/jdk1.1.6/demo

has many demo programs

and of course, Sun’s home page has the JDK distribution.

BR


Summary l.jpg
Summary particular code meant for each type of event.

  • We studied Java classes and objects, object-oriented programming, applications and applets.

  • A good understanding of the event-model is necessary to write event-driven programs.

  • Graphics and awt features (buttons, panels etc.) will tremendously enhance the capabilities and presentation of the event driven programs.

BR


ad