71
CSE422 Tuesday (Sept. 16, 2003) Java Overview Java Overview CSE 422 CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!

CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

Embed Size (px)

Citation preview

Page 1: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE422 Tuesday (Sept. 16, 2003)

Java OverviewJava Overview

CSE 422CSE 422

Michigan State Universityprepared by Philip K. McKinley

presented by SeyedMasoud Sadjadi

These materials are excerpted from a course created by Arthur Ryman of IBM Toronto, and used at the University of Toronto. Thanks!

Page 2: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

2Java Overview by SeyedMasoud Sadjadi

AgendaAgenda

Introduction to Java (today)– What is Java?– Tools Overview– Language Overview

Advanced Topics (next session)– Error Handling– Multithreading– Networking

Page 3: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

3Java Overview by SeyedMasoud Sadjadi

What is Java?What is Java?

A concurrent, object-oriented programming language (OOPL)

A virtual machine (run-time environment) – can be embedded in web browsers (e.g. Netscape

Navigator, Microsoft Internet Explorer and IBM WebExplorer) and operating systems.

Portable, Dynamic, and Extensible

A set of standardized packages (class libraries)

Page 4: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

4Java Overview by SeyedMasoud Sadjadi

Java, A Concurrent OOPLJava, A Concurrent OOPL

Complete OOPL (not only structures into objects) Characteristics of both C++ and Smalltalk

– C++ Same syntax for expressions, statements and control flow Similar OO syntax (classes, access, constructors, methods, ... )

– Smalltalk Similar object model (single-rooted inheritance hierarchy, access to

objects via reference only) Compiled to a byte-code (initially interpreted) Dynamic loading Garbage collection

Concurrency and synchronization (threads)– Objects can force mutual exclusion of threads running inside them

Page 5: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

5Java Overview by SeyedMasoud Sadjadi

Java Virtual MachineJava Virtual Machine

Java is complied to byte-codes whose target architecture is the Java Virtual Machine (JVM)

The virtual machine is embeddable within other environments, e.g. web browser & operating sys.

Uses a byte-code verifier when reading in byte-codes.

The Class Loader for classes loaded over the network (enhances security).

Java VM

EnvironmentJava

Source

.java

Java Byte-code

.class

javac

Page 6: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

6Java Overview by SeyedMasoud Sadjadi

Portable, Dynamic, and ExtensiblePortable, Dynamic, and Extensible

Java runtime based on architecturally neutral byte-codes (per class)

Java Runtime

Native.dll

Native.dll

interpret

loaded classes (byte-codes)

.class files

call

load

Page 7: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

7Java Overview by SeyedMasoud Sadjadi

Standard Set of PackagesStandard Set of Packages

Windowed GUIs– Full set of standard window-based GUI classes– Extremely easy to build GUI clients

Images and audio– Support for creating Image objects from .gif, .jpg, etc.– Provides Image processing “filters”– Applets can also play audio files

Networking– Library supports retrieving files, images, etc. via URL– Clean support for sockets providing access to Internet-

based services– VM can dynamically load classes over the Internet

Page 8: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

8Java Overview by SeyedMasoud Sadjadi

AgendaAgenda

Introduction to Java (today)– What is Java?– Tools Overview– Language Overview

Advanced Topics (next session)– Error Handling– Multithreading– Networking

Page 9: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

9Java Overview by SeyedMasoud Sadjadi

JDK ToolsJDK Tools

Java Developer’s Kit’s (JDK) three main tools are:– javac the Java compiler– java VM for running stand-alone Java applications– appletviewer a utility to view applets

Also included are:– javah Header file generator for interlanguage linking– javap A disassembler– javadoc HTML generator from Java source code– jdb a rudimentary Java debugger

Page 10: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

10Java Overview by SeyedMasoud Sadjadi

JIT CompilerJIT Compiler

Although Java is interpreted, Just-In-Time compilers provide “client-side” compilation of byte-codes to machine code (native binary)

This provides:– Improved performance– Better match to specific hardware

JVM running Applet or

Application

J.I.T.Compiler

.class

machine code

Page 11: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

11Java Overview by SeyedMasoud Sadjadi

EclipseEclipse

jdt: java development tools subproject – Plug-ins for Java development

Page 12: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

12Java Overview by SeyedMasoud Sadjadi

AgendaAgenda

Introduction to Java (today)– What is Java?– Tools Overview– Language Overview

Advanced Topics (next session)– Error Handling– Multithreading– Networking

Page 13: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

13Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 14: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Java ProgramsJava Programs

Two broad categories of program can be written

– Applet a Java program that runs inside a Java-enabled

Web browser.

– Application a Java program run via the “java” command.

Page 15: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

A Simple Java ApplicationA Simple Java Application

import java.io.*;

/** File: Count.java*/public class Count {` public static void main (String[] s) throws IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has "+count+" chars"); }}

• Compile the .java file to generate the .class filecmd>javac Count.java

• Run the interpreter on the .class filecmd> java CountThis is a test.Input has 16 chars

Page 16: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

AnalysisAnalysis

All Java code is contained within classes. Java classes consist of fields (variables) and methods. A Java source file contains at most one public class. Applications must provide a method called main. To be recognized,

the main method must have the correct method signature. Java stores collections of classes in packages (class libraries). The

import keyword selects the packages available.

import java.io.*;

/** File: Count.java*/public class Count {` public static void main (String[] s) throws IOException { int count = 0; while (System.in.read() != -1) count++; System.out.println("Input has "+count+" chars"); }}

Page 17: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

CommentsComments

There are different types of comments// single line comment (until eol)

/* single/multi-line comment (do not nest) */

/** multi-line documentation comment.

Use immediately before class, method, and variable declaration. The javadoc utility will use this comment to automatically generate HTML. May also include HTML and use optional tags:

<B> Here is a bolded comment <\B>

@author Neil Bartlett

@param d a number

@return sqrt of the number*/

Page 18: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

18Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 19: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Variables and IdentifiersVariables and Identifiers

Variable may be a primitive data type or reference to an object

Unicode 1.1 character set used (16 bit international character set encoding). This applies to the char data type.

An identifier starts with:– a letter (from any language encoded by Unicode)– an underscore (_), or– a dollar sign($)

Subsequent characters may be letters or digits or both Identifiers can be any length Identifiers may not be a reserved word or a boolean literal

(true, false)

Page 20: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Data Types - Primitive TypesData Types - Primitive Types

Primitive Type Precision Default Value byte 8 bits 0 short 16 bits 0 int 32 bits 0 long 64 bits 0 char 16 bits '\u0000' float 32 bits +0.0f double 64 bits +0.0d boolean - false No variable can have an undefined value Class variables are implicitly initialized to the default

unless set explicitly Local variables are not implicitly initialized to a default

Page 21: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Scope of a VariableScope of a Variable Scope is the block of code in which a variable is

accessible.– member variable. Declared within a class but not within a method.– local variable. Declared within a method or within a block.– method parameter. Values passed into method (more later)

class MyClass {

float myMethod( float f ) {

float f1;

{ // define a block inside a method just for fun

float f2 = 10F;

f1 = f2;

}

float f3 = f1;

return f*f3+i;

}

int i = 0;

}

i

ff1

f2

f3

Page 22: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Access SpecifiersAccess Specifiers

Specifies who may access variables. Also applies to classes, constructors, and methods.

public– available everywhere

protected– available only to the current class and its subclasses

private– available only to the class in which it is declared. This

is applied at the class not the object level. package

– If no access specifier is explicitly, available only within the current package

Page 23: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

23Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 24: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Flow of Control - ConditionalFlow of Control - Conditional

if (condition) { statements;} else { statements;}

switch (intVal) {case intVal1:

statements;break;

case intVal2:statements;return;

default:statements;break;

}

Page 25: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

for (initialize; test; increment){ statements;}

while (condition) { statements;}

do { statements;} while (condition);

goto // reserved word that does nothing!break label;continue label;

restart: for (int i = start; i < a.length ; ++i) { // mess with start if (a[i] == ';')

continue restart; }

Flow of Control - LoopingFlow of Control - Looping

Page 26: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

26Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 27: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Creating ObjectsCreating Objects

Objects are instances of classes. To declare an object, use the class name (the

type) and a identifier, e.g.Date today;

A variables stores reference to an object. The declaration does not create an object.

Objects are created with the new reserved word. This will create the memory for the object and return a reference to the object

today = new Date(); Or, using one step

Date today = new Date();

Page 28: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

The new operatorThe new operator

The new operator creates an object by allocating memory. Takes one parameter - the class constructor. The class

constructor is a special method declared in the class. It is responsible for initializing the object to a known state.Rectangle r = new Rectangle(0, 0, 100, 200);

Constructors have the same name as the class. A class can have more than one constructor, e.g.

Rectangle r = new Rectangle(100, 200);

Constructors typically set up the object's variables and other initial state. They might also perform some initial behavior.

Page 29: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Objects and ReferencesObjects and References

A variable stores a reference to an object. There is no equivalent of C++ pointer.

Many objects references may refer to the same object

MyClass o1 = new MyClass();

MyClass o2 = o1; Both o1 and o2 now refer to the same object

Comparing variables that refer to objects just compares the references. It does not compare the objects.

Integer i1 = new Integer(10);

Integer i2 = new Integer(10);

if (i1 == i2) {

// not true

}

o1 o2MyClass Object

Page 30: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

30Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 31: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

ArraysArrays

Arrays are objects in Java. Use new to create them. Arrays are fixed length. Length cannot be changed once

created. Indexes start at zero. Indexes are bounds checked.

Primitive Arraybyte[] bArray = new byte[5];

for (int i=0; i < bArray.length; i++)

bArray[i] = 42; // value Object Array

Date dArray[] = new Date [5];

for (int i=0; i < dArray.length; i++)

// Must now create the date objs

dArray[i] = new Date (); //ref

Page 32: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Multidimensional ArraysMultidimensional Arrays

Implemented as arrays of arrays

int twoDArray[][] = new int[300][400];

– Declares a variable of type int[][]– Dynamically allocates an array of with 300 elements– Allocates arrays of 400 ints for each element of the 300 element

array

Can provide partial sizing

int threeDArray[][][] = new int[10][][];

Multidimentional arrays need not be rectangular

int threeDArray[][][] = new int[10][][];

threeDArray[0] = new int[100][4];

threeDArray[1] = new int[3][5000];

Page 33: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Initializing ArraysInitializing Arrays

Arrays may be initialized with static initializersint lookup_table[] = {1, 2, 3, 4, 5, 6, 7, 8};

This is equivalent toint lookup_table[] = new int[8];

lookup_table[0] = 1;

Similarly for multidimentional arraysString param_info[][] = {

{"fps", "1-10", "frames per second"},{"repeat", "boolean", "repeat image loop"},{"imgs","url","images directory"} };

Page 34: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

StringsStrings

Strings are objects, not primitives Not null-terminated, not array of char Rich set of string manipulation methods Initializing

– must construct a string object, String s does not create an object

– String a = "abc" eqv. String a = new String("abc")

Concatenation operator, "abc"+"def" String class is non-mutative Use StringBuffer class for strings that change

Page 35: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

35Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 36: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Declaring MethodsDeclaring Methods

Must declare the data type of the value it returns. If no value is returned, it must be declared as returning void.

Methods may take arguments. These are values that are passed into the method when it is called. Arguments are typed and named. If names conflict with the class level variables, the argument names will hide the class level variable names.

Methods are scoped for the whole class. No need for forward references.

Java is very strongly typed. No equivalent of C variable length argument list.

Cannot pass methods into methods. (Methods are not a type)

Page 37: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Passing Arguments to MethodsPassing Arguments to Methods

Arguments are passed by value. Changing the value inside the method does not effect the value outside the method. This applies to both primitive types and object references.

public class myClass {int x;void myMethod(myClass ac, int ay) {

ay = 10; ac.x = 5; ac = null;

}public static void main (String args[]) { myClass c = new myClass(); c.x = 1000; int y = 2000; c.myMethod(c, y); System.out.println("c:"+c+" c.x:"+c.x+" y:"+y);}

}

Page 38: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

38Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 39: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Declaring ClassesDeclaring Classes

A class is declared using the class keywordclass myClass {

// class body

}

A class is by default accessible (e.g. can create objects of the class) from any other classes in the same package.

The public keyword can be used to create a class that is available anywhere.

Page 40: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

ConstructorsConstructors

Constructors are called by the new operator when a class is created. The constructor initializes the new object.

class myClass {

int x;

String s;

myClass() {

x = 10;

S = "Hello";

}

}

Constructors have no return type, but they may take arguments. The argument types must match those provided by the new operator.

myClass(int x, String s) { … }

myClass c = new myClass(10, "Hello");

Page 41: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Default ConstructorDefault Constructor

If no constructor is present a default constructor will be provided by the compiler.

The default constructor has no arguments and just calls the super class's constructor.

class myClass {

myClass() {

super();

}

}

Does not provide default constructor with arguments

Page 42: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Class Variables and MethodsClass Variables and Methods

Problem: If all method calls need an object, how to we provide global constants and utility functions. Must we create an object just to use them?

Classes can provide variables and methods that may be used with out an object. There are called class variables and class methods.

To make a variable or method into a class variable, use the static keyword, e.g. static int count;

In contrast variables and methods of objects are called instance methods and instance variables.

Class methods may directly use other class methods and class variables. If they want to use an instance methods or variables, they must instantiate objects.

class method may not be overridden.

Page 43: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Examples of Class Variables and Examples of Class Variables and MethodsMethods

import java.util.*;

public class ClassMethodExample {

static String todaysDate() {

Date d = new Date();

return d.toString();

}

public static void main(String[] s) {

System.out.println( "The square root of pi is "+

Math.sqrt( Math.PI ));

System.out.println( "The date is "+todaysDate() );

}

}

main method is a class method. It does not require an object. Math and System are part of the core java packages.

– They provide useful math and system functions and constants. These are implemented as class methods and class variables.

todaysDate is a user-defined class method. It constructs a Date object to do its job.

Page 44: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

44Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 45: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

InheritanceInheritance

To inherit a class from another class use the extends keyword

class SubClass extends SuperClass {

...

}

The sub class inherits variables and methods from its super class. It also inherits variables and methods from the super class of the super class and so on up the inheritance tree.

Java has single inheritance. A class can only have one super class.

Page 46: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

The Object classThe Object class

Every class you define has a super class. There is a special class called Object which is the implicit super class of any class which does not explicitly descend from a class, so

class MyClass

is equivalent to class MyClass extends Object

Object is the root class of all classes. The Object class provides generic methods for all objects. These

include:– getClass. Returns an object that contains information about the class that

the object was created from.

– toString. Provides a generic string detailing the object.

– clone. A placeholder method to allow copying of an object

– equals. A method to compare objects.

Page 47: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

What's Inherited?What's Inherited?

When one class extends from another, the sub class inherits those variables and methods that:– are declared with the public or protected access specifiers.

– have no access specifier But don't inherit those

– with the same name a one in the sub class.

– declared as private.class SuperClass {

int x, y;

int methodA() {…}

int methodB() {}

}

class SubClass extends SuperClass {

int y; // hides SuperClass.y

int methodB() {} // overrides SuperClass.methodB

}

Page 48: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

48Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 49: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Polymorphism - Method HidingPolymorphism - Method Hiding

A method with the same signature as a method in its super class hides or overrides the method in the super class.

An object of a sub class may be assigned to a reference of a super class. In this case, these overridden methods will be calledclass SuperClass {

void aMethod() { … }

}

class SubClass {

void aMethod() {…}

}

SuperClass s = new SubClass();

s.aMethod(); // calls SubClass's aMethod

Page 50: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

The final keywordThe final keyword

The final keyword is used to limit what can be changed when it is inherited It can be applied to:

classes. A final class cannot be extended from. Generally you do this for security reasons , e.g. the String class

final class MyClass methods. This stops a method from being overridden in

a subclass. The method may still be called by the subclass.

final double sqrt(double d) variables. This declares a constant value. The value is

available to the subclass but it may not change or shadow the value.

final int useful_constant=10;

Page 51: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

this and superthis and super

In method body, this is a reference to the current object and super is a reference to its parent.

class A {Object x;

}class B extends A {

float x; float calculate(){ … }}class C extends B {

int x;void m(char x) {

char cmx = x; //the method argumentint cx = this.x; //C’s member xfloat bx = super.x; //B’s x, also B.xObject ax = A.x; //A’s x

} float calculate() {return super.calculate();}}

Page 52: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

52Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 53: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Abstract ClassesAbstract Classes

Super classes that define generic behaviours that must be implemented by derived classesabstract class DiscPlayer {

protected int track;void setTrack() { /* cue the track to play*/ }public abstract void play();

}

class VideoDiscPlayer extends DiscPlayer {public void play() { /* play the video disk */ }

}

class MultiCDPlayer extends DiscPlayer { protected int currentCD;

public void play() { /* play the current CD */ }}

DiscPlayer explicitly provides some responsibility while deferring other responsibility to its subclasses.

Page 54: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Abstract Classes and MethodsAbstract Classes and Methods

An abstract class may contain zero or more abstract methods. Any class that contains an abstract method is implicitly abstract.

An abstract class cannot be instantiated. An abstract method must be implemented in a subclass to instantiate

an object of the subclass. Abstract methods can provide implementation. This is useful to

provide default processing: class SuperClass {

abstract void aMethod() { /* something useful */ }

}

class SubClass extends SuperClass {

void aMethod() {

super.aMethod();

...

Page 55: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

InterfacesInterfaces

An interface specifies methods that must be implemented. The interface does not implement the methods; The methods are implemented by the class that implements the interface. public interface Runnable {

public abstract void run ();}class A implements Runnable {

public void run() {// do something

}}

All interfaces are public. All methods of interfaces are implicitly public and abstract

Also permitted as part of an interface are public static final fields.public interface myInterface {

public static final aConstant=100;}

Page 56: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Class Inheritance Vs. InterfacesClass Inheritance Vs. Interfaces

Interfaces define only method signature. Inherited classes can provide implementation.

Can only have one super class. Can implement a number of interfacesclass A implements Runnable, Printable

{

Choose class inheritance for strongest isA relationship. Choose interfaces for behavior (Note frequent use of the suffix -able for interface names)

Page 57: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

57Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 58: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Garbage CollectionGarbage Collection

The runtime reclaims storage asynchronously using a garbage collector. The garbage collector frees the memory associated with any objects that do not have references.

The garbage collector runs in a low-priority thread. It is also called if the memory system runs out of memory to allocate.

Use System.gc() to explicitly force garbage collection For variables that do not go out of scope, but that you still

want to be garbage collected, set the object reference variable to null. This removes the reference to the underlying object.

obj = null;

Page 59: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

FinalizeFinalize

A class may request finalization of its instances by implementing a finalize() methodprotected void finalize () throws Throwable {

/* cleanup */;

super.finalize();

}

Note that this method may NOT have any other method modifiers associated with it.

When an object is first detected to be unreferenced, the finalize method is invoked (if present). If it is subsequently determined to be unreferenced, the object is reclaimed. All uncaught exceptions occurring during finalization are ignored.

Page 60: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

60Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 61: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

The Class classThe Class class

The Class class contains information about a class. This allows us to provide runtime type information (RTTI)

There is a Class object for each class that has been loaded.

The Class class allows information about the class to be inspected, e.g. getName, getInterfaces, getSuperClass.

The Object class has a method getClass which will return a class object.

// print out the name of the class of an object

String objClassName = obj.getClass().getName();

Page 62: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Class LoadingClass Loading

Classes are loaded dynamically by the system from .class files. When a class is first referenced, a store of classes is checked, if the

class has not been loaded, it is loaded. Classes can be dynamically loaded under program control. The Class

class has a method forName which takes a String of the name of the class and returns a Class object.

Any blocks inside the class that are marked as static are run when the class first loads.

class myClass {

static {

System.loadLibrary("mylib.dll");

}

}

Page 63: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Advanced Object CreationAdvanced Object Creation

It is not necessary to use the new operator to create an object.

Objects can be created from a just a name. Objects of the Class class provide the newInstance

method to create an instance of the class, e.g.Class aClass = Class.forName ("myClass");

Object o = aClass.newInstance (); This is often used to load subclasses of superclass, e.g. a

game player might be allowed to upload new monsters. In this case it is necessary to cast the returned classString monsterClassName = getNameFromUser();

Class aClass = Class.forName (monsterClassName);

Monster m = (Monster) aClass.newInstance ();

Page 64: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

64Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 65: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Compilation UnitsCompilation Units

Classes and interface are defined in a compilation unit (a file)

A compilation unit declares zero or more classes. At most, one declared type (class or interface) may be declared public.

For a compilation unit which declares a public type ClassName, the file must be named ClassName.java.

Multiple classes in a compilation unit will result in multiple .class files after compilation

Page 66: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

PackagesPackages

Packages are used to logically group together classes. Each .class file is part of a package. Package is declared using the

package operator. This must form the first statement in the source.

package mypackage; If no package is explicitly stated, then the package is unnamed. All

'unpackaged' classes in the directory in which the .class file resides are part of this package.

Package names have a one-to-one correspondence to a directory. Package names are dot separated (e.g., java.lang)

Packages can be imported by other source files:– Example:

import packagename.*;

import packagename.classname;

Page 67: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

The CLASSPATHThe CLASSPATH

The CLASSPATH is an environment variable used to locate packages.

The CLASSPATH consists of a series of directories separated by semi-colons (Windows) and colons (UNIX).set CLASSPATH = d:\mydir;c:\java

Each directory forms the root directory to search for a package. Thus if the package were java.lang, there must be a directory called java under one of the directories in the CLASSPATH and there must be a directory call lang under that, for the package to be found.

Page 68: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

68Java Overview by SeyedMasoud Sadjadi

Language OverviewLanguage Overview

Java Programs Variables Flow Control Objects Arrays Methods Classes Inheritance Polymorphism Abstract Classes

Garbage Collection Reflection Packaging Java vs. C++

Page 69: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

Java vs. C++Java vs. C++

Java does not: have pointers and pointer

arithmetic

have structs, unions, enums

have templates

support operator overloading

support multiple inheritance

have any standalone functions

support default arguments for methods

have a delete operator

have variable arguments

make use of a preprocessor

synchronous destructors

Java does have:

different compilation model (compiles to byte-codes per class)

single-rooted class inheritance hierarchy

multiple interface inheritance

strings and arrays are true objects

garbage collection

support for concurrency via Threads

Page 70: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

70Java Overview by SeyedMasoud Sadjadi

AgendaAgenda

Introduction to Java (today)– What is Java?– Tools Overview– Language Overview

Advanced Topics (next session)– Error Handling– Multithreading– Networking

Page 71: CSE422 Tuesday (Sept. 16, 2003 ) Java Overview CSE 422 Michigan State University prepared by Philip K. McKinley presented by SeyedMasoud Sadjadi These

CSE 422 09/16/2003

Java Overview by SeyedMasoud Sadjadi

SummarySummary

Java is a full-featured OOP language– Single-implementation inheritance– Multiple-interface inheritance

Java has a similar syntax to C++ but different semantics

Portable Garbage Collection Dynamic Loading Reflection