introduction to java n.
Download
Skip this Video
Download Presentation
Introduction to Java

Loading in 2 Seconds...

play fullscreen
1 / 130

Introduction to Java - PowerPoint PPT Presentation


  • 98 Views
  • Uploaded on

Introduction to Java. Dr. Billy Lim Applied Computer Science Department Illinois State University. Objectives. Upon completion of this course, you will be able to Understand the architecture of Java technology Use the various programming language features of Java

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 'Introduction to Java' - blair-cain


Download Now 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
introduction to java

Introduction to Java

Dr. Billy Lim

Applied Computer Science Department

Illinois State University

objectives
Objectives
  • Upon completion of this course, you will be able to
    • Understand the architecture of Java technology
    • Use the various programming language features of Java
    • Develop basic Java applications
    • Write OO applications using Java
why java
Why Java?
  • Observations …
    • 4 million Java programmers and the community is growing at the rate of 30 percent a year
    • Java is now running on everything from smart cards to the Mars Rover
    • Java 2 Platform, Standard Edition v 1.4 hits the million mark
      • In less than a month, the latest version of J2SE has been downloaded over a million times
    • More than 20,000 attendees in a recent Java developer conference (JavaOne)
    • 100-million Java Consortium formed by some of the biggest software companies (IBM, Oracle, …)
    • Number of Fortune 500 adopting Java
    • More than 1/2 millions Java developers
    • … (many many more!)
history of java
History of Java
  • “Java’s ancestor was a toaster!”
  • Began life as a programming language for consumer electronics
  • C/C++ not up to task! (not chip-independent)
history of java 2
History of Java (2)
  • 1990: James Gosling at Sun designing a language called “Oak”, a small, reliable, architecture-independent language
  • 1993: WWW appeared and took Internet “by storm”
  • Gosling and his team thought, “hey, this is bigger than we thought.”
history of java 3
History of Java (3)
  • Sun wrote a new WWW browser named HotJava
    • First browser to support Java applets However, only “alpha” Java API
  • Netscape later announced Java support
  • Later a beta API, and soon a Java 1.0 API released
  • The rest is history
what is java
What is Java?
  • From “The Java Language: A White Paper” (by Sun):

“A simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language”

simple
Simple
  • What’s simple?
    • Can learn quickly
    • Looks familiar
    • Poor programming features removed (e.g., no goto)
    • No pointers
    • Garbage collection - no memory leaks
object oriented
Object-Oriented
  • OO is ubiquitous!
    • Lots of commercially produced code in C++ (and Java, Smalltalk, etc.)
  • Focus on data, not procedures
  • Encapsulates data and functions
  • More “natural”
  • Exploits inheritance
  • (Almost) Everything in Java is an object!
distributed
Distributed
  • Designed to support applications on networks
    • Applets downloaded over the net
    • Resources accessed via URLs
  • Socket class built in
    • easy to write
      • clients and servers, collaborative programs
  • Reliable stream network connections
  • Furthers goal towards making the network is the computer
interpreted
Interpreted
  • Java compiler’s output is in “byte-code” format
  • Must run an interpreter to run these bytecodes
    • Java Virtual Machine (JVM) is the interpreter
    • may be realized by software or hardware
    • JVM is built into AppletViewer, Netscape, IE, HotJava, etc. These bytecodes are architecture-neutral
architecture neutral
Architecture-Neutral
  • Bytecodes run on any machine, as long as an interpreter exists
  • Neutrality helps programmers -- no porting required
    • Unlike C/C++, no implementation-dependent features (e.g., int is always 4 bytes)
  • Using the AWT, we can create architecture-neutral windowing applications!
    • Abstract Windowing Toolkit (AWT) and “peer” classes give appropriate “look and feel”
architecture neutral 2
Architecture-Neutral (2)

Java Source

Java Compiler

Java Bytecode

JVM

JVM

JVM

JVM

Windows

Solaris

OS390

Mac

“Write Once, Run Anywhere”

robust
Robust
  • Highly reliable
  • Helped by:
    • Strong typing features
    • Object-orientation
    • Java Memory Model
    • No Pointers
    • Garbage Collection
    • Exception Handling
secure
Secure
  • Security is very important in networked environments
  • No pointers
  • Applet only: Can’t access any computers other than host
  • Evolving security measures
    • JDK 1.02: sandbox (e.g., no disk I/O for applets)
    • JDK 1.1: signed applets
    • JDK 1.2 and beyond: “security policy” (with the SecurityManager class)
  • JVM enforces restrictions on applets
  • JAVA does not stand for “Just Allow Virtually Anything”
portable
Portable
  • Makes sure there are no implementation-dependent aspects
  • Strong API
  • Java compiler: written in Java
  • Java run-time system: written in ANSI C
high performance
High-Performance
  • Interpreted: won’t be as fast as C (getting closer every day though!)
  • Performance-critical applications: JIT (“just in time”) compilers
  • HotSpot technology (Sun), Jikes (IBM)
  • Native methods
  • The spectrum:
    • Tcl/Tk, shells < Java <= C and C++
multithreaded
Multithreaded
  • Multiple things at once
  • Supports multiple threads of execution (lightweight processes)
    • garbage collection thread
    • sound and animation
  • Java has built-in support for synchronization primitives
    • Thread class built in
    • synchronized keyword
dynamic
Dynamic
  • Dynamic class loading, as required, possibly over the net
  • Classes have run-time information
  • These classes can be anywhere on the Internet
  • All of this run-time loading is invisible to user
how do i use java on the net
How Do I Use Java (on the net)?
  • Web Users
    • transparent to you
  • Web Page Designers
    • use the <APPLET> tag in HTML
    • thousands of applets out there!
  • Java Developers
    • create Java applets, servlets (“server-side applets”), and/or JSP (Java Server Pages)
java editions
Java Editions
  • Free download from http://java.sun.com
    • J2SE (Java 2 Standard Edition)
    • J2EE (Java 2 Enterprise Edition)
    • J2ME (Java 2 Micro Edition)
j2se software development toolkit sdk
J2SE Software Development Toolkit (SDK)
  • javac
    • Java compiler, converts .java to .class
    • All Java source codes must be stored in files with .java extension
  • java
    • Java virtual machine (i.e., the interpreter)
  • javadoc
    • generates HTML documentation from Java source files (/** … */ segment)
  • appletviewer
    • allows applet to be run outside of a browser
  • jar
    • Java archive tool (JDK 1.1 only)
  • javah
    • Java C header and stub generator
  • jdb
    • Java Debugger
sdk cont d
SDK (cont’d)
  • Java Package Library
    • java.lang, java.io, java.awt, java.net, java.util, java.applet (JDK 1.02)
    • java.beans, java.sql, java.rmi, … (a lot more) etc. (JDK 1.1, Java 1.2, Java 1.3)
  • JDK available in:
    • Unix platforms
    • Windows 95/98/NT/2000
    • OS/2
    • Macintosh
    • Windows 3.1
    • OS 390

And more!!!

java ide tools
Java IDE Tools
  • Eclipse (Apache Open Source Project)
    • Based on IBM VisualAge for Java
  • IBM WebSphere Application Developer (WSAD)
  • BlueJ
  • Borland JBuilder
  • Oracle JDeveloper
  • Symantec Visual Café
  • Sun Forte for Java
  • ...
first java program hello world
First Java Program: Hello, World!

// This is a comment

// The file is named HelloWorld.java

publicclass HelloWorld {

publicstaticvoid main(String args[]) {

System.out.println(“Hello World!”);

}

}

  • Note: If the class is public, the name of the class (i.e., HelloWorld) must be the same as the name of the file plus the .java extension (i.e., HelloWorld.java)
main not quite so simple anymore
main(): Not quite so simple anymore
  • In Java, we can’t simply write main()
  • We have to create main as a method in a Java class which returns nothing (void)
  • Furthermore, we must make this method public and static
    • public: Anything can call it
    • static: It belongs to the class itself, not a instance of the class
println explained
println explained
  • What exactly is System.out.println(“...”)?

System is a classIt has a class variable named outout refers to an object of type PrintStreamPrintStream objects have an instance method named println

QED

a java program skeleton
package MyPackage; // used if adding class to a package

import packageName; // used if a package/class is to be “loaded”

accessType class ClassName extends SuperClass {

// Field Declarations are given here

accessType dataType fieldName;

private int salary;

// Method Definitions are given here

accessType returnType methodName (parameter list) {

… // method body

}

public void print () {

System.out.println(“Salary is ” + salary);

}

}

A Java Program Skeleton

Bold - keywords

ClassName.java

Access Types:

private

public

protected

default = “friendly”

applications and applets
Applications and Applets
  • Applications are stand-alone
    • No security restrictions
  • Applets are designed for the web
    • Security restrictions
    • Integrates with HTML
    • Shows up in WWW browser

In the last few years, two other kinds of Java programs have

been introduced – Servlets and JSPs

the hello world applet
The “Hello World” Applet

// HelloApplet.java

import java.awt.*;

import java.applet.*;

publicclass HelloApplet extends Applet {

Font f = new Font(“TimesRoman”, Font.BOLD, 36);

publicvoid paint(Graphics g) {

g.setFont(f);

g.setColor(Color.red);

// draw string at x=5, y=50 (pixels)

g.drawString(“Hello World!”, 5, 50);

}

}

edit compile run cycle in java
Edit-Compile-Run Cycle in Java

.java (source file)

Compiler (e.g., javac )

.class (bytecodes)

Java VM (e.g., java)

output

how to compile and run
How to Compile and Run
  • Compile a source code file by typing

javac <filename>.java(e.g., javac HelloWorld.java)

    • If no compile-time error appears, a .class file is produced.
  • Run an application by typing

java <class name>(e.g., java HelloWorld)

Not java HelloWorld.class

features similar to c c s
Features Similar to C/C++’s
  • Same comment styles
    • new: /** to be processed by javadoc … */
  • Same literals and data types
    • new: true and false for the boolean data type
    • new: strings not null terminated, not mutable
    • new: numeric sizes and their machine independence
  • Same operators
  • Same control structures
java s basic constructs
Java’s Basic Constructs
  • Comments
    • // comment on one line
    • /* comment on one or more lines */
    • /** documenting comments */
  • Statements
    • int x; // statement ends with a semicolon (;)
    • x = 1 + 2;
primitive data types
Primitive Data Types
  • There are 8 primitive data types in Java
    • All the numeric types (integer and floating point types) are signed (meaning they can be positive or negative). No unsigned numeric types in Java (unlike C/C++).
  • Three categories of data types:
    • Primitive data types
    • Class data types (coming later)
    • Interface data types (coming later)
basic data types
Integers

byte (8 bits)

short (16 bits)

int (32 bits)

long (64 bits)

Characters

char (16 bits Unicode)

Floats

float (32 bits)

double (64 bits)

Boolean

boolean (1 bit)

Strings

String (an example of class data type)

Basic Data Types

Primitive data types

capital case (because it is a class, not a primitive)

identifiers and literals
Identifiers and Literals
  • Identifiers
    • case sensitive
    • have no maximum length
    • start with a letter, underscore, or dollar sign
      • e.g., user_name, _file, $money
  • Literals
    • numeric: 2 (int), 3L (long), 2.0f (float) 3.14 (double), 077 (octal), 0xDC (hex)
    • character: ‘a’, ‘t’
    • boolean: true, false
    • string: “hello”

Watch out for these!

booleans
Booleans
  • Has value true or false (different from numeric type)
  • Returned by relational operators
  • Required for conditional statements
  • E.g.,
    • // if x is an int
    • C/C++: if (x) { ...} // OK in C/C++, not OK in Java
    • Java: if (x == 1) { ...}
strings
Strings
  • String is a “built-in” class provided by Java
    • e.g., String s1 = “Hi there!”;
  • The ‘+’ operator is used for String concatenation
    • e.g., String s1 = “abc”;
    • String s2 = s1 + “ ” + s1;
  • String objects represent constant strings (content cannot be altered)
  • Many methods supported in the String class
strings 2
Strings (2)
  • Examples
      • String lastName = “Schaefer”;
      • lastName.length() // gives 8
      • lastName.toUpper() // gives “SCHAEFER”
      • lastName.toLower() // gives “schaefer”
      • lastName.indexOf(“e”) // gives 4
      • lastName.indexOf(“x”) // gives –1 (for not found)
      • lastName.indexOf(“e”,5) // gives 6
      • lastName.substring(2,5) // gives “hae” (1st index is inclusive, 2nd index is exclusive)
declarations assignments
Declarations & Assignments

// TestDataType.java

public class TestDataType {

public static void main(String[] args) {

int x = 1;

float y = 3.1415f;

boolean truth = true;

char c = ‘X’;

String str1 = “Hello”, str2 = “World”, str3;

str3 = str1 + str2;

System.out.println("x="+x+"y="+y+"truth="+truth+"c="+c+"str3="+str3);

System.out.println(“Length of str3 = “ + str3.length());

}

}

Syntax (first look):

objectRef.methodName(argument list)

Note: If the + operation has a string involved, a concatenation of all the operands is performed.

Java automatically converts all data involved to their string representations.

operators
Operators
  • Partial list (in order of precedence):
    • ++, --
    • !, (type)
    • *, /, %
    • +, -
    • <, >, <=, >=, instanceof
    • ==, != (equal to and not equal to operators, respectively)
    • && (this is the logical AND operator)
    • || (this is the logical OR operator)
    • =, *=, /=, +=, ...
  • ++ (Preincrement, Postincrement) // increments a variable by 1
  • e.g., x = 1; System.out.println(x++); // displays 1
  • System.out.println(x); // displays 2
  • e.g., x = 1; System.out.println(++x); // displays 2
  • System.out.println(x); // displays 2
  • -- (Predecrement, Postdecrement) // decrements a variable by 1
  • e.g., x = 1; System.out.println(x--); // displays 1
  • System.out.println(x); // displays 0
  • e.g., x = 1; System.out.println(--x); // displays 0
  • System.out.println(x); // displays 0
casting and promotion
Casting and Promotion
  • Casting
    • conversion of one data type to another data type
    • Two ways to cast in Java:
      • implicit - Java does it for you automatically
        • For primitives, if expression on the right differs from the type of the variable on the left, automatic cast will happen if no possibility of losing information. The narrower data type will be promoted to the wider one.
        • For objects, later on this.
      • explicit - the programmer must take care of the casting
        • For primitives, if expression on the right differs from the type of the variable on the left and there is a possibility of losing information.
        • For objects, later on this.
promotion and casting
Promotion and Casting
  • e.g., // TestDataType2.java

int x, y = 1;

double z = 1.23;

x = y / z; // compilation error

x = y / (int) z; // OK

x = (int) (y / z); // OK

z = x; // OK

decision structures
Syntax (if, else):

if (boolean expr) {

statements;

} else {

statements;

}

Example:

int status;

...

if ( status == 1) {

deduction = 500;

marriedCount ++;

} else {

deduction = 100;

singleCount ++;

}

Decision Structures

Note: else part is optional

decision structures 2
Syntax (switch):

switch (expr) {

case expr1:

stmt1;

break;

case expr2:

stmt2;

break;

default:

stmt;

break;

}

Example:

switch (status) {

case 1:

marriedCount++;

break;

case 2:

singleCount ++

break;

default:

// error;

break;

}

Decision Structures (2)
looping structures
Looping Structures
  • Syntax (for):

for (initial expr; boolean expr; update expr) {

statements;

}

  • Example:

for (int k = 0; k < 10; k++) {

System.out.println(k);

}

looping structures 2
Syntax (while):

while (boolean expr) {

statements;

}

Examples:

int k = 0;

while (k < 10) {

System.out.println(k);

k++;

}

keepGoing = ‘y’;

while (keepGoing == ‘y’) {

// determine if you need to keep going

}

Looping Structures (2)
arrays
Arrays
  • Arrays are objects
  • Like C/C++, subscripts start from 0
  • No pointers in Java => no pointer arithmetic
  • To create an array,
    • use “new”
      • e.g., int a[] = new int[5]; // creates an array of 5 ints
      • same as: int [] a = new int[5];
    • or array initializer
      • int a[] = {1, 2, 3, 4, 5};
  • To access an array element, use a[i] where 0 <= i < arraySize
  • Array boundaries are checked at runtime
arrays cont d
Arrays (cont’d)
  • The following will throw an exception (can be caught and handled)
    • e.g., int a[] = new int[5];

a[5] = 123; // array out of bound exception

  • Can use length to determine array size
    • e.g., publicvoid doSomething ( int a[] ) {

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

a[i] = 0;

}

Passing an int array into a method

arrays cont d1
Arrays (cont’d)
  • Creating an array of objects:
    • Student classList [] = new Student[25];
    • classList[0] = new Student();

null

null

null

classList

null

aStudent

null

null

classList

null

arrays cont d2
Arrays (cont’d)
  • Initial values:
    • // TestArray1.java
    • String names [] = {“John”, “Mary”};

or

String names [] = new String [2];

names[0] = “John”;

names[1] = “Mary”;

    • Can’t do this:
      • int list[5]; // error: Can’t specify array dimension in type declaration
      • int list2[]; // OK; declares list to be an array of int but does not allocate any space for it yet
      • list2[0] = 1; // error: because list2 has not been not allocated any space.

// Need to use: int list2[] = new int[10];

arrays cont d3
Arrays (cont’d)
  • Cannot resize arrays
    • int myArray[] = new int[5]; // myArray is an array of 5 ints
    • myArray = new int[10]; // myArray is a different array, with 10 ints

// Will discuss this further in Objects

  • Copying arrays
    • Use System.arraycopy method
    • int copyFrom[] = {10, 20};
    • int copyTo[] = {100, 200,300};
    • System.arraycopy(copyFrom,0, copyTo,0, copyFrom.length);
    • Result: copyTo has {10,20,300};
multi dimensional arrays
Multi-Dimensional Arrays
  • Arrays of arrays

int twoDim [][] = new int [4][];

twoDim [0] = new int [5];

twoDim [1] = new int [5];

twoDim [2] = new int [5];

twoDim [3] = new int [5];

    • Alternatively,

int twoDim [][] = new int [4][5];

command line arguments
Command Line Arguments
  • The entry point to your Java application must have the following method:
    • public static void main (String argv[]) {...}
  • argv[] must be present -- it holds the command line arguments
  • argv[0] gives the first argument
  • Use argv.length to get the number of arguments
command line arguments 2
Command Line Arguments (2)
  • e.g., // TestCmdLine.java

public class TestCmdLine {

public static void main (String argv[]) {

if (argv.length == 0)

System.out.println(“No argument given!”);

else

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

System.out.println(argv[i]);

}

}

naming conventions
Naming Conventions
  • Methods & variables:
    • Mixed case, starting with lower-case for the first word and each subsequent word starts with a capital letter
    • E.g.,: myFirstMethod(), myBankAccount
  • Classes & interfaces:
    • Mixed case, starting with upper-case for the first letter of the first word and each subsequent word starts with a capital letter
    • E.g.,: MyClass, MyInterface
naming conventions cont d
Naming Conventions (cont’d)
  • Constants:
    • Upper case, with words separated by underscores
    • E.g.,: MY_LARGE_CONSTANT
  • Packages:
    • All lower-case letters in all the words
    • E.g.,: com.billylim.project1
classes
Classes
  • A class is a template (i.e., blueprint) for creating objects
  • A class extends another class (inheritance relationship)
    • e.g., public class className extends superclassName {

...

}

  • By default, all classes are derived from a single root class called Object
  • All classes except Object have one immediate superclass
classes 2
Classes (2)

// Student.java

public class Student {

private String name; // name is a field, attribute, or an instancevariable

public Student(String n) { // This is a constructor. Note that it has the

name = n; // same name as the class name. More on this later.

}

public void setName (String n) {

name = n;

}

public String getName () {

return name;

}

public void print () {

System.out.println(“Name is “+name);

}

}

The getter and setter methods. Typically, get

and set methods are defined for each field.

If a field is named, say, workAddr, then a get

method named getWorkAddr() and a set method

named setWorkAddr(…) are created.

classes 3
Classes (3)

// TestStudent.java (a dummy class to test the functionality of the Student class)

public class TestStudent {

public static void main (String argv[]) {

Student s1 = new Student("Lee");

Student s2 = new Student("John");

s2.setName("John Jr.");

s1.print();

System.out.println(s2.getName()); // can also use print() here

}

}

  • Note: The Student and TestStudent classes need to be in the same directory for the above to work properly.
objects
Objects
  • Objects/instances of classes are created using “new”
    • e.g., Student s = new Student(“John”);
  • A variable of non-primitive type actually holds “handle” for the actual object. It is called an object reference.
  • Assigning objects copies the handle, not the object.
objects 2
Objects (2)
  • Example:

Student s1 = new Student(“Lee”); s1

Student s2 = s1; s1

s2

s2.setName(“Lee JR.”); // whose name is changed?

Aside: This is why System.arraycopy is needed to copy arrays

Lee

Lee

objects 3
Objects (3)
  • Example:

Student s1; // s1 has the value null

s1 = new Student(“John”); s1

s1 = new Student(“Mary”);

s1

s1 = null; // what is the effect of this?

John

John

John will be garbage collected

Mary

fields
Fields
  • Field creation
    • Syntax:
      • accessTypedataTypefieldName;
    • Example:
      • privateinthoursWorked;
      • privateStringname;
  • Field use
    • Syntax:
      • fieldName (if inside the class)
      • objectReference.fieldName (if outside the class and if the field is accessible)
    • Example:
      • if (hoursWorked < 40) … // inside class
      • employee1.hoursWorked = 37; // outside class

optional

methods
Methods
  • Methods
    • defined the behaviors of a class (called member functions in C++)
    • can only be implemented in classes (no standalone code)
    • must have a return type unless they are constructors (which have no return type)
    • must have a comma separated list of pairs of parameter types and names (if takes no parameter, the list is empty)
method definition
Method Definition

optional

  • Syntax:

[accessType] [modifier(s)] returnTypemethodName (parameter list) {

… // method body

}

  • Examples:

publicstaticvoidmain(String[] args) {

}

privateintmyMethod(int j, String s) {

}

StringmyMethod2( ) {

}

constructors
Constructors
  • Special methods that have the same names as their classes
  • Are invoked during the creation of an object by “new”
  • Constructors do not have a return type
  • Constructors (and methods in general) can be overloaded by varying the number of types of parameters
constructors 2
Constructors (2)
  • Default constructor
    • A default constructor is automatically provided for you in every class
      • Format: public MyClass() { // assume class name is MyClass

}

    • Allows you to do:

MyClass mc = new MyClass( );

    • Will be invalidated if you add a constructor declaration with arguments
access specifiers
Access Specifiers
  • As with C++, components of classes can have associated access specifiers
    • public Accessible by all
    • protected Only accessible from this class, its subclasses, and package.
    • private Only accessible from this class
    • “friendly” Accessible from the package; Default access (no specific declaration)
access specifiers 2
Access Specifiers (2)
  • Accessibility Criteria

Modifier Same Class Same Package Subclass All

public Yes Yes Yes Yes

protected Yes Yes Yes

Default Yes Yes

private Yes

access specifiers 3
Access Specifiers (3)
  • Examine the classes Employee.java and TestAccess.java in your source disk.
  • Compile the class TestAccess.java and observe the output. (Should see an error message.)
  • Now change the name and salary fields to public and re-compile and run TestAccess.java.
  • Lesson: Keep instance variables/fields private!
argument parameter passing
Argument/Parameter Passing
  • Java passes arguments by value only
  • When an object reference is passed as an argument to a method, a copy of the object reference is passed.
    • Thus, the contents of the actual object can be changed in the method, but the object reference itself is never changed.
argument parameter passing1
Argument/Parameter Passing
  • Example:

public static void main (String args[]) {

int a = 10;

String s = “hello”;

Employee e = new Employee (“Mary”);

method1(a, s, e);

System.out.println(“a =“+a+”s=“+s+”e”+e); // prints 10, hello, and John

}

public static void method1 (int a2, String s2, Employee e2) {

a2 = 100;

s2 = “hello2”;

e2.setName(“John”);

e2 = new Employee(“Matt”);

}

class inheritance
Class Inheritance
  • We can “inherit” from other classes
  • Avoids coding things which have already been coded (i.e. reuse the structure and behavior already implemented)
  • Subclass inherits everything from the superclass, but programmer can add/change things in the subclass
  • Commonly referred to as the “is-a” relationship (also called Generalization/Specialization relationship)
  • We use the keyword extends to inherit in Java
inheritance 1
Inheritance (1)

Fields:

f1, f2, and f3

Superclass

Methods:

m1,m2, m3, m4, m5, and m6

All the fields and methods are inherited by the subclass

Fields:

f4 and f5

Methods:

m6,m7, m8, and m9

A subclass may add additional fields (f4-f5) and/or methods (m7-m9) and/or override an existing one (m6)

Subclass

An object of Superclass:

An object of Subclass:

Has 3 “slots” and understand messages m1-m6

Has 5 “slots” and understand messages m1-m5, m6 (as defined in the subclass) and m7-m9

inheritance 2
// Person.java

public class Person {

private String name;

public Person (String n) {

name = n;

}

public void setName (String n) {

name = n;

}

public String getName () {

return name;

}

public void print () {

System.out.println(“Name is

“+name);

}

}

// Student2.java

public class Student2 extends Person {

private float gpa;

public Student2 (String n, float g) {

super (n); // calls superclass constructor

gpa = g;

}

public void setGpa (float g) {

gpa = g;

}

public float getGpa () {

return gpa;

}

public void print () { // overriding

super.print(); // calls superclass print()

System.out.println("gpa is” +gpa);

}

}

Inheritance (2)
inheritance 3
Inheritance (3)

// TestPersonStudent.java

public class TestPersonStudent {

public static void main (String argv[]) {

Person p = new Person("Joe");

p.print();

Student2 s = new Student2("Joe", 0.0f);

s.setName("Joe Jr."); // setName is inherited

s.setGpa(4.00f);

s.print();

}

}

overriding vs overloading
Overriding vs. Overloading
  • Overriding
    • Subclass can specialize the methods of the superclass by changing the operation of a method declared by the superclass without changing the interface.
    • Overridden method can be invoked using super
    • Same method name, same parameter list, same return type, different body
  • Overloading
    • A class can enhance its functionality by providing a means for the user to call a method with a different number of arguments or type.
    • Same method name, same or different return type, different parameter list, different body
overloading example
class Person {

private String name;

// overloaded constructor with no parameter

public Person () {

name = “ ”;

}

// overloaded constructor with 1 parameter

public Person (String n) { name = n;

}

public void setName (String n) { … }

public String getName () { … }

public void print () { … }

}

public class TestPerson {

public static void main (String argv[]) {

Person p1 = new Person();

p1.print();

Person p2 = new Person(“John”);

p2.print();

}

}

Overloading: Example
this and super keywords
this and super Keywords
  • Sometimes it is necessary to refer to the instance of the object itself within a method or to refer to the superclass within a subclass.
    • Use this to refer to the object itself
    • Use super to refer to the super class
slide87
this
  • Every instance method has a variable named this associated with it
  • thisrefers to the current object for which the method is being called
  • The this variable is used implicitly by the compiler when your method refers to an instance variable of the class
this example
this: Example

public static void main (String args[]) {

Student s1 = new Student (“John”);

Course c1 = new Course(“Java”);

c1.addAStudent(s1); // add student “John” to the course “Java”

}

public class Course {

...

public void addAStudent (Student s) {

add(this, s); // Let’s say this method can’t handle the add itself.

// It needs to pass the necessary info to another method.

}

private void add (Course c, Student s) { // note that this is a private method

… // real processing here

}

}

this another example
this: Another Example

public static void main (String args[]) {

Person p = new Person (“John”);

}

public class Person {

private String name;

public Person (String name) {

this.name = name;

}

}

parameter

field

this yet another example
this: Yet Another Example

public class Student2 extends Person {

public Student2 () {

this(“unknown”); // calling an overloaded constructor

}

public Student2 (String name) {

this(name,0.0f); // calling an overloaded constructor

}

public Student2 (String name, float gpa) {

super(name);

this.gpa = gpa;

}

}

super example
super: Example

class Student extends Person {

private float gpa;

public Student (String n, float g) {

super (n);

gpa = g;

}

}

  • Note: When using super and this in a constructor, it must be the first thing you do! i.e., super and this must be the 1st line.
  • Cannot use “super.super.varOrMethodName” to access a hidden variable or method two levels up in the inheritance hierarchy
abstract classes
Abstract Classes
  • An abstract class allows the specifications of incomplete method definitions in a class (the methods are called abstract methods). The incomplete definitions are to be completed in the subclasses that inherit from the abstract class.
  • Benefits:
    • subclasses know the interface specified
    • subclasses are forced to implement the interface
      • “A Parent gets to tell its children what to do!”
  • Note: Abstract classes cannot be instantiated.
abstract classes example 1
Abstract Classes: Example (1)

Fields:

1. accountHolder

2. balance

Account

Methods:

1. Gets and sets for the fields

2. deposit

3. withdraw

Can be made “incomplete,”

i.e., give only the interface but not the implementation

CheckingAccount

SavingsAccount

deposit() and withdraw() methods must be overridden by the CheckingAccount and SavingsAccount classes in order for them to be treated as a “concrete” class. If not, they become abstract as well.

abstract classes example 2
abstract public class Transportation {

private int speed;

public abstract void transport (int speed);

public abstract void print ();

public void setSpeed (int s) {

speed = s;

}

public int getSpeed () {

return speed;

}

}

public class Car extends Transportation {

public void transport (int speed) { // drive

setGear();

pressPedal();

}

public void print () {

System.out.println("Speed =”

+getSpeed());

System.out.println("Other Car

related information");

}

pubic void setGear() { … };

public void pressPedal() { … };

}

Abstract Classes: Example (2)

Note the semicolon (i.e., no method implementation here; just the interface)

oo characteristics pie
OO Characteristics: PIE
  • Polymorphism
    • Late binding mechanism
  • Inheritance
    • Through the use of extends
  • Encapsulation
    • Class mechanism
    • private access specifier
polymorphism
Polymorphism
  • In Greek it means “many forms”
  • In OO/Java it means
    • “one interface, multiple implementations” (e.g., a print interface with multiple implementations from the Person and Student classes)
    • “One object reference, possibly referring multiple forms of objects” (e.g., Person x; Here x can be a Person, Student, etc.)
      • Note: an object has only one form but an object reference can be of multiple forms (we say the object reference variable is polymorphic).
polymorphism example

public class HappyPerson {

public void laugh() {

System.out.println("Laugh Laugh Laugh");

}

}

public class Student3 extends HappyPerson {

public void laugh() {

System.out.println("HaHaHa");

}

}

public class Professor3 extends HappyPerson {

public void laugh() {

System.out.println("HeeHeeHee");

}

}

Polymorphism: Example

...

public static void main (String args[]) {

HappyPerson list [] = new HappyPerson[3];

list[0] = new Student3();

list[1] = new Professor3();

list[2] = new HappyPerson();

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

list[i].laugh();

}

...

Output?

the instanceof operator
The instanceof operator
  • When you are passed a polymorphic reference variable, sometimes you want to know what you actually have. Can find out using the instanceof operator.
  • Example:

public void method1 (HappyPerson p) {

if (p instanceof Student) {

// Do something with a Student object

// e.g., Student s = (Student) p;

// The above fully restores the functionality of the object as a student

// Without the cast, can’t perform: p.getGpa();

// OK to say: s.getGpa();

else if (p instanceof Professor) {

// Do something with a Professor object

else {

// Do something with a regular happy person object

}

}

casting objects
Casting Objects
  • Use instanceof to test the type
  • Use casting to fully restore the functionality of an object
  • Rules:
    • Casts up hierarchy are done implicitly
      • E.g., Person p = new Student();
    • Downward casts must be done explicitly and are checked by the compiler
      • E.g., Student s = (Student) p; // where p is of type Person
    • Object type is checked at runtime (runtime error may result)
      • E.g., Student s = (Student) p; // where p is of type Person and it is

// actually referring to a person object

has a relationship
“has-a” Relationship
  • Oftentimes a relationship is of type “has-a” (also called association) instead of “is-a.”
    • E.g., A car has an engine, an employee has a department that he/she works for, etc.

class Car {

private Engine e;

}

class Employee {

private Department d;

}

the operator vs equals
The == operator vs. equals()
  • The == operator performs equivalence test, i.e., x==y returns true if and only if x and y are referring to the same object.
  • The equals() method is overridden in classes in order to return true if the contents and type of two separate objects match
    • Note: if not overridden, the Object class will return false unless the two objects are the same.
example of vs equals
Example of == vs. equals()

public class TestEqual {

public static void main(String argv[]) {

Student s1 = new Student("Billy");

Student s2 = new Student("Billy");

if (s1 == s2)

System.out.println("s1 == s2");

if (s1.equals(s2)) // equals() should have been overridden to return true

System.out.println("s1 equals s2");

String str1 = new String("abc");

String str2 = new String("abc");

if (str1 == str2)

System.out.println("str1 == str2");

if (str1.equals(str2))

System.out.println("str1 equals str2");

String str3 = "abc";

String str4 = "abc";

if (str3 == str4)

System.out.println("str3 == str4");

if (str3.equals(str4))

System.out.println("str3 equals str4");

}

}

Output

str1 equals str2

str3 == str4

str3 equals str4

the final keyword
The final Keyword
  • Variables declared final must have a value assigned in their declarations. Attempt to change the variables will result in compilation error.
    • final int x = 10;
  • Methods declared final may not be overridden.
    • final void cannnotOverride();
  • Classes declared final may not be subclassed.
    • final public class lastClass { … };
static variables
Static Variables
  • static Variables
    • Only one copy of the variable is kept for all objects of the class (a class variable as opposed to an instance variable)
    • e.g., public class Employee {

static private String workAddress;

}

static methods
Static Methods
  • static Methods
    • can only access static variable of the class
    • implicitly final

e.g., // Professor.java

public class Professor {

static private String workAddress;

private String name;

public void setWorkAddress (String addr){

workAddress = addr;

}

public static void setName (String n) {

name = n; // compile-error!

// Need to remove static is this case

}

public void print() {

System.out.println("workAddress = " + workAddress);

System.out.println("name = "+name);

}

}

// TestStatic.java

public class TestStatic {

public static void main (String argv[]) {

Professor p = new Professor();

p.setName("Billy");

p.setWorkAddress("ACS 5150, ISU");

p.print();

}

}

static methods 2
Static Methods (2)
  • Invoking static Methods

e.g., // Professor2.java

public class Professor2 {

static private String workAddress;

private String name;

public static void setWorkAddress (String addr){

workAddress = addr;

}

public void setName (String n) {

name = n;

}

public void print() {

System.out.println("workAddress = " + workAddress);

System.out.println("name = "+name);

}

}

// TestStatic2.java

public class TestStatic2 {

public static void main (String argv[]) {

Professor2 p = new Professor2();

p.setName("Billy");

p.setWorkAddress("ACS 9999, ISU, Normal, IL 61790");

p.print();

Professor2.setWorkAddress("ACS 1, ISU, Normal, IL 61790");

p.print();

}

}

Syntax (first look):

class.methodName(argument list)

static methods 3
Static Methods (3)
  • Another static method example:

public class TestStatic3 {

public static void main (String argv[]) {

method1(); // Error: TestStatic3.java:3: Can't make static reference to method

// void method1() in class TestStatic3.

}

public void method1 () { // Need to add “static” to remove the error above

method2(); // Possible to call method2 if it is to remain a non-static method?

}

public void method2 () {

System.out.println("method2 called!");

}

}

concept of packages
Concept of “Packages”
  • Obscene amount of Java classes on the net
  • Need a way to hierarchically classify them
  • Use an “inverse domain approach”
    • e.g., edu.ilstu.acs.java.HelloWorld
    • e.g., com.ibm.ivj.examples.TicTacToe
  • This allows us to place our classes on the Internet/Intranet/Extranet without fear of collision
  • Usually only need this for end result
packages 2
Packages (2)
  • package keyword enables grouping of classes
  • Package names are dot.separated (.) words and are stored in directories that match the words
    • e.g., java.Util.Date, java.Util.Dictionary, java.net.URL, ...
  • Package declaration must be specified at the beginning of the source file (only one permitted)

package com.xyz.dept1;

public class Employee { …}

packages 3
Packages (3)
  • Accessing packages using import
    • class packages are loaded with the import keyword, specifying the package name as the path and the class name.
    • Load multiple classes within a package with * (a class is not loaded until it is actually referenced in your code).
    • e.g., import java.util.Date;

import java.awt.*;

import com.xyz.dept1.*;

    • Note: import java.awt.*; brings all classes in java.awt into the current namespace (does not load them). Also, it does not bring any (sub)packages! Need to use: import java.awt.event.*; if classes from java.awt.event are to made visible.
packages 4
Packages (4)
  • Classpath Environment Variable
    • In order for the compiler to locate a class, say, com.xyz.dept1.Employee, the classpath environment variable must be defined in the following way:

set classpath=C:\com\xyz\dept1;. (Windows)

setenv classpath=/com/xyz/dept1;. (Unix)

java packages
Java Packages
  • Java language provides a suite of packages
    • java.applet (applet functionality)
    • java.awt (GUI components)
    • java.io (I/O and file I/O stream classes)
    • java.lang (language basics; automatically loaded)
    • java.net (TCP/IP networking protocols)
    • java.util (miscellaneous classes)
    • java.beans (component model)
    • java.sql (JDBC database support)
    • java.rmi (remote method invocation, distributed computing)
    • ...
exceptions
Exceptions
  • To help you build resilient code by allowing to catch error (i.e., exceptions) that are thrown and to handle the exception, when possible.
  • The Exception class defines mild error conditions that your program encounters and might want to handle
    • Examples:
      • NullPointerException (attempt to access an undefined object or method), ArithmeticException (typically result of zero division), ArrayIndexOutOfBoundsException (array index out of bound)
  • The Error class defines serious error conditions (that your program should not try to recover from)
    • Examples:
      • OutOfMemory
exception classes
Exception Classes
  • Class hierarchy:

Object

+--- Throwable

+--- Error

+--- VirtualMachineError

+--- StackOverFlowError

+--- OutOfMemoryError

+--- Exception

+--- RunTimeException

+--- ArithmeticException

+--- NullPointerException

+--- IndexOfBoundsException

+--- ArrayIndexOfBoundsException

+--- ...

+--- IOException

+--- FileNotFoundException

...

+--- ...

Don’t need to handle these

exception handling
Exception Handling
  • Java provides exception handling facilities to find out what exception was thrown and try to recover
  • try and catch
    • use the try statement with code that might throw an exception that you are to handle
    • use the catch statement to specify the exception to catch and the code to execute when caught
    • e.g., try {

// code that might throw an exception

} catch (SomeExceptionType e) {

// handle exception here

}

exception handling 2
Exception Handling (2)
  • finally statement
    • defines a block of code that is always executed, regardless of whether an exception is caught or not.
    • E.g. [Yellin],

try {

startFaucet();

waterLawn();

} catch (BrokenPipeExceptionType e) {

// handle exception here

} finally {

stopFaucet();

}

exception handling example
Exception Handling: Example

try {

int x = 0;

int y;

y = 1/x;

System.out.println(“Testing 123…”);

} catch (ArithmeticException e) {

System.out.println(“Div by 0”);

} finally {

System.out.println(“Clean Up, always!”);

}

System.out.println (“Testing 456…”);

Output:

Div by 0

Clean Up, always!

Testing 456…

more exception handling
More Exception Handling

What if an exception is not caught?

… main(String args[]) {

try{

method1(…);

}

catch (Exception1 e){

// Code to handle exception1

}

catch (Exception e){

// Code to handle a generic exception

}

finally{

// Code always to be executed

}

}

void method1(…) {

method2(…);

}

uncaught

Exception1

propagated

Exception1

caught

void method2(…) {

method3(…);

// Exception1 thrown

// from method3

}

uncaught

Exception1

propagated

interfaces
Interfaces
  • Interfaces are in the Java language mainly to provide much of the functionality of multiple inheritance, but without the difficulties.
  • Common usage:
    • Java guarantees that if you “implement(s)” an interface, you actually provide the necessary method(s).
  • A scenario:
    • Want Car and Boat to also have “Collectible” behavior

Transportation

Collectible

Car

Boat

interfaces 2
Interfaces (2)
  • Definition (of an interface):
    • a collection of method signatures (without implementations, always public and abstract) and/or constants (always public, static, and final) that can be added to a class to provide additional behaviors not defined in the class itself or inherited from its superclasses
  • Syntax:
    • // To create an interface:

public interface MyInterface [extends Interface1, Interface2, ...] {

// all methods here are defaulted to public and abstract.

// all variables here are defaulted to final, static, and public.

}

    • // To use an interface:

public class MyClass implements MyInterface {

// must implements all the methods specified in the interface MyInterface

}

interfaces 3
public interfaceComparable {

public int compare(Sortable obj);

}

public class Student2 extends Person implementsComparable {

private float gpa;

… // all the methods from Student2 discussed earlier

public int compare(Comparable obj) {

Student2 s = (Student2) obj;

return (gpa < s.gpa)? -1: 1;

}

}

public class Sort {

static void bubbleSort(Comparable [] sortArr) {

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

for (int j = i; j < sortArr.length; j++) {

Comparable temp = sortArr[i];

if ( temp.compare(sortArr[j]) > 0 ) {

temp = sortArr[j];

sortArr[j] = sortArr[i];

sortArr[i] = temp;

} // if

} // for

} // bubbleSort

} // Sort

Interfaces (3)
interfaces 4
Interfaces (4)

public class TestInterface {

public static void main(String args[]) {

Student2 stuArr[] = new Student2[10];

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

int rand = (int) (10 * Math.random());

String name = String.valueOf(rand);

float gpa = (float) (4 * Math.random());

stuArr[i] = new Student2(name, gpa);

}

Sort.bubbleSort(stuArr);

for (int j = 0; j < stuArr.length; j++)

stuArr[j].print();

}

}

interfaces 5
Interfaces (5)
  • Notes:
    • Interfaces are very commonly used in the AWT and the event model
      • public class MyClass implements ActionListener {

public void actionPerformed(…) { …}

}

    • Interfaces can extend multiple interfaces
wrapper classes
Wrapper Classes
  • Used for wrapping primitive data types so that they can be used as objects

Primitive data typesWrapper classes

boolean Boolean

byte Byte

char Character

short Short

int Integer

long Long

float Float

double Double

wrapper classes cont d
Wrapper Classes (cont’d)
  • Example:
    • int myInt = 1;
    • Integer wrapperInt = new Integer (myInt);
    • // do something with wrapperInt (e.g., insert it into a Vector)
    • myInt = wrapperInt.intValue();
    • int myInt2 = Integer.valueOf(“12345”).intValue();
the vector class
The Vector Class
  • Provides methods for working with dynamic arrays of varied elements
    • Maintains a capacity and capacityIncrement. As elements are added, storage for the vector increases in chunks the size of the capacityIncrement
    • Useful for dynamically storing heterogeneous collection of elements
the vector class 2
import java.util.*;

public class TestVector {

public static void main(String args[]) {

MyVector v = new MyVector() ;

int digit = 5;

float real = 3.14f;

String s = new String ("Hi there!");

v.addInt(digit);

v.addFloat(real);

v.addString(s);

v.printVector();

}

}

class MyVector extends Vector {

public void addInt(int i) {

addElement(new Integer(i)); // requires Object arg

}

public void addFloat(float f) {

addElement(new Float(f));

}

public void addString(String s) {

addElement(s);

}

public void printVector() {

Object o;

int length = size();

System.out.println("Number of vector elements is " + length + " and are:");

for (int i = 0; i < length; i++) {

o = elementAt(i);

System.out.println(o.toString());

}

}

}

The Vector Class (2)
references
References
  • Java Programming, Sun Microsystems, 1996-99.
  • Howell, Developing in Java, IBS, 1996.
  • Cornell & Horstmann, Core Java, 2nd Edition, Prentice-Hall, 1997.
  • van der Linden, P., Just Java and Beyond, 3rd Edition, Prentice-Hall, 1998.
  • http://www.cs.ucla.edu/csd-grads-gs2/decuir/java/
ad