introduction to java. java characteristics object-oriented distributed platform independent secure...

96
Introduction to Java

Upload: christine-carroll

Post on 12-Jan-2016

240 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Introduction to Java

Page 2: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java characteristics

• Object-oriented

• Distributed

• Platform independent

• Secure

• Strongly typed

Page 3: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java 2 platform

• Java virtual machine: execute byte code, just in time (jit) compilation

• Java 2 enterprise edition (J2EE): service and enterprise applications

• Java 2 standard edition (J2SE): desktop and personal applications

• Java 2 Micro edition (J2ME): embedded and consumer devices

Page 4: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

J2SE

• Java virtual machine: java• Tools: compiler javac, debugger jdb, Java class

disassembler javap, documentation generator javadoc,

• Core APIs: java.lang, java.util, java.io, java.net, java.security, etc.

• GUI APIs: java.awt, javax.swing, javax.sound• Integration APIs: javax.rmi, java.sql (JDBC),

javax.naming (JNDI), org.omg.CORBA

Page 5: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

J2EE

• Superset of J2SE

• Java servlet (javax.servlet) and Java Server Pages (JSP) (javax.servlet.jsp)

• Enterprise Java Beans (EJB) javax.ejb

• Email and messaging services javax.mail

• Transaction management javax.transaction

Page 6: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

J2ME

• Connected device configuration (CDC) for devices with large amount of memory and high network bandwidth

• Connected, limited device configuration (CLDC) for devices with limited memory, low bandwidth, intermittent network connections

• KVM runs on PDAs and cell phones

Page 7: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java runtime architecture

byte codeinterpreter

CPU

byte codecompiler

CPU

nativemachine code

Java CPU

Java byte code

Java compiler

Java source code

JVM

Java machine

Platform independent

Platformdependent

JVM

Page 8: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java byte code

• Byte code format• pc program counter• optop top of stack• vars local variables• frame execution environment• Garbage-collected heap• RISC like instruction set, 32-bit register• Stack-based architecture

opcode (1-byte)

operand1operand2

Page 9: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

JVM instruction functions

• Stack manipulation

• Array management

• Arithmetic/logical operations

• Method invocation/return

• Exception handling

• Thread synchronization

Page 10: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

JVM security

• Strong typing: no pointers, array bound checks, dynamic downcast checks

• Byte code verification: loaded class files satisfy byte code specification

• Run time access control: discretionary access control based on stack inspection, flexible security policy

Page 11: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 12: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

OO programming concepts• What Is an Object? An object is a software bundle of related

variables and methods. Software objects are often used to model real-world objects you find in everyday life.

• What Is a Message? Software objects interact and communicate with each other using messages.

• What Is a Class? A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.

• What Is Inheritance? A class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs.

• What Is an Interface? An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.

Page 13: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 14: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Language basics

• public class BasicsDemo { public static void main(String[] args) {

int sum = 0; for (int current = 1; current <= 10;

current++){ sum += current;

} System.out.println("Sum = " + sum);

} }

Page 15: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Language basics

• Variables

• Operators

• Expressions, statements, and blocks

• Control flow statements

Page 16: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Variables

• Definition:  A variable is an item of data named by an identifier

• Data Types

• Variable Names

• Scope

• Variable Initialization

• Final Variables

Page 17: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Data types

• Primitive Data Types:– Integers: byte, short, int, long (8 – 64 bits)– Real numbers: float, double (32, 64 bits)– Others: char (16 bit unicode), boolean

• Arrays, classes, and interfaces are reference types• The value of a reference type variable, in contrast

to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable

Page 18: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Variable names

• It must be a legal identifier• It must not be a keyword, a boolean literal (true

or false), or the reserved word null• It must be unique within its scope• By Convention: Variable names begin with a

lowercase letter and class names begin with an uppercase letter

• If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter (for example, isVisible)

Page 19: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Scope

• A variable's scope is the region of a program within which the variable can be referred to by its simple name

• Scope determines when the system creates and destroys memory for the variable

• if (...) {int i = 17; ..

}System.out.println("The value of i = " + i); //error

Page 20: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Variable initialization

• Local variables and member variables can be initialized with an assignment statement when they're declared

• Parameters and exception-handler parameters cannot be initialized in this way. The value for a parameter is set by the caller

Page 21: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Final variable

• The value of a final variable cannot change after it has been initialized. Such variables are similar to constants in other languages

• final int aFinalVar = 0; // or• final int blankfinal;

. . . blankfinal = 0;

Page 22: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Language basics

• Variables

• Operators

• Expressions, statements, and blocks

• Control flow statements

Page 23: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Operators

• Arithmetic Operators: +, -, *, /, %, ++, --• Relational (>, <, >=, <=, ==, !=) and

Conditional Operators (&&, ||, &, |, !, ^) • Shift (<<, >>, >>>) and Bitwise Operators (&,

|, ~, ^) • Assignment Operators (=, op =) • Other Operators: op1 ? op2 : op3, new,

op1 instanceof op2, [], ., (params), (type)

Page 24: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Expressions, statements, blocks• An expression is a series of variables,

operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value

• A statement forms a complete unit of execution

• A block is a group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed

Page 25: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Control flow statements

Statement Type Keywordlooping while, do-while, for decision making if-else, switch-case exception handling try-catch-finally, throw Branching break, continue, label:,

return • control flow statement details {

statement(s) }

Page 26: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 27: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Object basics

• The Java platform groups its classes into functional packages

• Instead of writing your own classes to represent character, string, or numeric data, you should use the classes that are already provided by the Java platform

• Most of the classes discussed here are members of the java.lang package

Page 28: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Creating objects

Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne,

100, 200);

Rectangle rectTwo = new Rectangle(50, 100); 1.declaration2.instantiation3.initialization

Page 29: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using objects

• Directly manipulate or inspect its variables

• Call its methods • objectReference.variableName • int height = new Rectangle().height • objectReference.methodName(argumentList);

or objectReference.methodName(); • int areaOfRectangle = new Rectangle(100,

50).area();

Page 30: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Cleaning up unused objects

• The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection

• An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null

Page 31: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Simple data objects

• Characters and strings

• Numbers

• Arrays

Page 32: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Characters and strings

• When working with character data, you will typically use either the char primitive type, or one of the following three classes: – String — A class for working with immutable

(unchanging) data composed of multiple characters. – StringBuffer — A class for storing and manipulating

mutable data composed of multiple characters. This class is safe for use in a multi-threaded environment.

– StringBuilder — A faster, drop-in replacement for StringBuffer, designed for use by a single thread only.

Page 33: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Characters

• char ch = 'a'; char[] • firstFiveLetters={ 'a', 'b', 'c', 'd', 'e' }; • char ch = string.charAt(i); • //Test whether a character is upper case.

if (Character.isUpperCase(string.charAt(i)) { ... }

• //Convert a character to lower case. char ch = Character.toLowerCase(string.charAt(i));

• //Determine if the character is a letter. if (Character.isLetter(string.charAt(i))) { ... }

Page 34: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Strings • If your text is not going to change, use a string — a String

object is immutable. • If your text will change, and will only be accessed from a

single thread, use a string builder. • If your text will change, and will be accessed from multiple

threads, use a string buffer• public class StringsDemo {

public static void main(String[] args) { String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); StringBuilder dest = new StringBuilder(len); for (int i = (len - 1); i >= 0; i--) {

dest.append(palindrome.charAt(i)); } System.out.format("%s%n",

dest.toString()); } }

Page 35: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Strings and compiler• The compiler uses the StringBuilder class behind the scenes to handle

literal strings and concatenation

• int len = "Goodbye Cruel World".length(); • String s = "Hola Mundo";

The preceding construct is equivalent to, but more efficient than, this one, which ends up creating two identical strings:

String s = new String("Hola Mundo"); //don't do this

• String cat = "cat"; System.out.println("con" + cat + "enation"); The preceding example compiles to something equivalent to: System.out.println( new StringBuffer().

append("con").append(cat).append("enation").toString()); • int one = 1;

System.out.println("You're number " + one);

Page 36: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Number classes

• Two reasons that you might use a Number class, instead of the primitive form: – When an object is required — such as when using generic types.

For example, to constrain your list to a particular type argument, such as String. You must specify the Integer type, as in ArrayList<Integer>

– When you need the variables or static methods defined by the class, such as MIN_VALUE and MAX_VALUE, that provide general information about the data type

Page 37: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Simple data objects

• Characters and strings

• Numbers

• Arrays

Page 38: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Arrays

• An array is a structure that holds multiple values of the same type.

• The length of an array is established when the array is created.

• After creation, an array is a fixed-length structure.

Page 39: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Creating and using arrays• public class ArrayDemo {

public static void main(String[] args) { int[] anArray; // declare an array of integers anArray = new int[10]; // create an array of

integers // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) {

anArray[i] = i; System.out.print(anArray[i] + " "); } }

} • You can write an array declaration like this:

float anArrayOfFloats[]; //this form is discouraged • new elementType[arraySize]; // create new array• boolean[] answers = { true, false, true, true, false }; //

initialize array • arrayname.length // get size of the array

Page 40: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 41: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 42: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Writing classes

Page 43: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Declaring classes

Element Function

@annotation (Optional) An annotation (also called meta-data)

public (Optional) Class is publicly accessible

abstract (Optional) Class cannot be instantiated

final (Optional) Class cannot be subclassed

class NameOfClass

Name of the class

<TypeVariables> (Optional) comma-separated list of type variables

extends Super (Optional) Superclass of the class

implements Interfaces

(Optional) Interfaces implemented by the class

{ ClassBody } Provides the class's functionality

Page 44: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Declaring member variables• private List<Object> items; • Element Function • accessLevel (optional) Access level for the

variable – public, protected, private, and default

• static (optional) Declares a class variable • final (optional) variable value cannot change • transient (optional) the variable is transient

– member variables that should not be serialized

• volatile (optional) the variable is volatile – Prevents the compiler from performing certain

optimizations on a member

• type name The type and name of the variable

Page 45: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Declaring methods• Element Function

• @annotation (Optional) An annotation (sometimes called meta-data)

• accessLevel (Optional) Access level for the method

• static (Optional) Declares a class method

• <TypeVariables> (Optional) Comma-separated list of type variables

• abstract (Optional) Indicates that the method must be implemented in concrete subclasses

• final (Optional) Indicates that the method cannot be overridden

• native (Optional) Indicates that the method is implemented in another language

• synchronized (Optional) Guarantees exclusive access to this method

• returnType methodName The method's return type and name

• ( paramList ) The list of arguments to the method

• throws exceptions (Optional) The exceptions thrown by the method

Page 46: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Providing constructors

• public Stack() { items = new ArrayList<Object>(); }

• public Stack(int size) {items = new ArrayList<Object>(size); }

• public, private, protected, default

Page 47: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 48: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Manage inheritance

All Classes are Descendants of Object

Page 49: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Inheritance

• Every class has one and only one direct superclass (single inheritance)

• A subclass inherits all the member variables and methods from its superclass

• a subclass cannot access a private member inherited from its superclass

• constructors are not members and so are not inherited by subclasses

Page 50: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Overriding and hiding methods• An instance method in a subclass with the same signature

and return type as an instance method in the superclass overrides the superclass's method

• a method's signature is its name and the number and the type of its arguments

• can also override a method with the same signature that returns a subclass of the object returned by the original method. This facility is called covariant return type

• A subclass cannot override methods that are declared final in the superclass

• A subclass must override methods that are declared abstract in the superclass, or the subclass itself must be abstract

Page 51: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Overriding and hiding methods

• You might want to use the @override annotation which instructs the compiler that you intend to override a method in the superclass

• If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass

• An instance method cannot override a static method, and

• A static method cannot hide an instance method

Page 52: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Hiding member variables

• A member variable that has the same name as a member variable in the superclass hides the superclass's member variable, even if their types are different

• Within the subclass, the member variable in the superclass cannot be referenced by its simple name, the member variable must be accessed through super

• we don't recommend hiding member variables

Page 53: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using super• If your method overrides one of its superclass's methods, you can invoke the

overridden method through the use of super

• public class Superclass { public boolean aVariable; public void aMethod() { aVariable = true; }

} public class Subclass extends Superclass {

public boolean aVariable; //hides aVariable in Superclass //not recommended

public void aMethod() { //overrides aMethod in Superclass

aVariable = false; super.aMethod(); System.out.format("%b%n", aVariable);System.out.format("%b%n", super.aVariable); } }

Page 54: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using super• The following example illustrates how to use the super

keyword to invoke a superclass's constructor• Suppose you are writing a transaction-based system and need

to throw a checked exception if the transaction fails. Such an exception should include an informative message and a reference to the cause of the problem, another exception, checked or unchecked (Throwable)

• public final class TransactionFailedException extends Exception {

static final long serialVersionUID = -8919761703789007912L

public TransactionFailedException(Throwable cause) {super("Transaction failed", cause)

}}

Page 55: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

What does Object class provide

• Object class defines the basic state and behavior that all objects might use, such as – the ability to compare oneself to another object, – to convert to a string, – to wait on a condition variable, – to notify other objects that a condition variable

has changed, and – to return the class of the object

Page 56: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Methods of Object class

• The methods of Object class that may need to be overridden by a well-behaved subclass– equals and hashCode– toString

• In addition, the Object class provides the following handy methods:– getClass (equivalent to Class.forname(“class

name”), or className.class)– notify, notifyAll, and wait

• there is finalize, a special method, called by the garbage collector. It shouldn't be called from regular programs

Page 57: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Final classes and methods• make a method final if it has an implementation

that should not be changed and it is critical to the consistent state of the object

• Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method to behave in surprising or undesirable ways

• declare an entire class final prevents the class from being sub-classed. This may be useful when creating an immutable class like the String class

Page 58: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Abstract class and methods• model an abstract concept without being able to create

an instance of it• abstract class Number { ... }• abstract methods have no implementation• abstract class GraphicObject {

int x, y..void moveTo(int newX, int newY) { ... }abstract void draw()

}class Circle extends GraphicObject {

void draw() { ... }}

Page 59: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 60: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Nested classes• class EnclosingClass {

…class ANestedClass { … }

}• define a class within another class when the

nested class makes sense only in the context of its enclosing class or when it relies on the enclosing class for its function

• a nested class has a special privilege: It has unlimited access to its enclosing class's members, even if they are declared private

• a nested class can be declared static (or not). A static nested class is called just that: a static nested class. A non-static nested class is called an inner class

Page 61: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Nested classes

• an inner class is associated with an instance of its enclosing class and has direct access to that object's instance variables and methods

• because an inner class is associated with an instance, it cannot define any static members itself

• nested class reflects the syntactic relationship between two classes

• inner class reflects the relationship between objects that are instances of the two classes

• two special kinds of inner classes: local classes and anonymous classes

Page 62: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

• interface Iterator<E> {public boolean hasNext(); public <E> next(); public void remove(); }

public class Stack { private ArrayList<Object> items; //code for Stack's methods and constructors not

shown public Iterator<Object> iterator() { return new

StackIterator(); } private class StackIterator implements Iterator {

int currentItem = items.size() - 1; public boolean hasNext() { ... } public ArrayList<Object> next() { ... } public void remove() { ... }

} }

Page 63: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Anonymous class• public class Stack {

private ArrayList<Object> items; // code for Stack's methods and constructors // not shown public Iterator<Object> iterator() {

return new Iterator<Object>() { int currentItem = items.size() - 1; public boolean hasNext() { ... } public ArrayList<Object> next()

{ ... } public void remove() { ... }

}; }

}

Page 64: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Local class• public class Stack {

private ArrayList<Object> items; //code for Stack's methods and constructors not

shown public Iterator<Object> iterator() {

private class StackIterator implements Iterator<Object>{

int currentItem = items.size() - 1; public boolean hasNext() { ... } public ArrayList<Object> next() { ... } public void remove() { ... }

} return new StackIterator();

} }

Page 65: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Summary of nested class

• A class defined within another class is called a nested class

• Like other members of a class, a nested class can be declared static or not

• A non-static nested class is called an inner class• An instance of an inner class can exist only within

an instance of its enclosing class and• has access to its enclosing class's members even if

they are declared private

Page 66: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Types of Nested Classes

• Type Scope Inner

• static nested class member no

• inner [non-static] class member yes

• local class local yes

• anonymous class where it is defined yes

Page 67: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 68: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Enumerated types

• enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY };

• The enum declaration defines a class (called an enum type)

• the constructor for an enum type is implicitly private

• If you attempt to create a public constructor for an enum type, the compiler displays an error message

Page 69: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

• public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH …; private final double mass; //in kilograms private final double radius; //in meters Planet(double mass, double radius) {

this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; } //universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; public double surfaceGravity() {

return G * mass / (radius * radius); } public double surfaceWeight(double otherMass) {

return otherMass * surfaceGravity(); } }

Page 70: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

• public static void main(String[] args) {double earthWeight =

Double.parseDouble(args[0]); double mass =

earthWeight/EARTH.surfaceGravity(); for (Planet p : Planet.values()) {

System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass));

} } Here's the output:

$ java Planet 175 Your weight on MERCURY is 66.107583 Your weight on VENUS is 158.374842 Your weight on EARTH is 175.000000 …

Page 71: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 72: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Annotations • Annotations provide data about a program that is

not part of the program • such as naming the author of a piece of code or

instructing the compiler to suppress specific errors • An annotation has no effect on how the code

performs• Annotations use the form @annotation and

may be applied to a program's declarations: its classes, fields, methods, and so on

• The annotation appears first and often (by convention) on its own line, and may include optional arguments

Page 73: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Annotations

• @Author("MyName") class myClass() { }

or @SuppressWarnings("unchecked") void MyMethod() { }

• there are three built-in annotations: – @Deprecated, – @Override, and – @SuppressWarnings

Page 74: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Annotations • import java.util.List;

class Food {} class Hay extends Food {} class Animal {

Food getPreferredFood() { return null; } /** @deprecated document why the method was

deprecated */ @Deprecated static void deprecatedMethod() {

} } class Horse extends Animal { Horse() { return; }

@Override Hay getPreferredFood() { return new Hay(); }

@SuppressWarnings("deprecation") void useDeprecatedMethod() {

Animal.deprecateMethod(); //deprecation warning - suppressed } }

Page 75: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Classes and inheritance

• Writing classes

• Manage inheritance

• Nested classes

• Enumerated types

• Annotations

• Generics

Page 76: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics • public class Library {

private List resources = new ArrayList(); public void addMedia(Media x)

{ resources.add(x); } public Media retrieveLast() {

int size = resources.size(); if (size > 0) { return resources.get(size - 1); } return null;

} } public class Media { } public class Book extends Media { } public class Video extends Media { }public class Newspaper extends Media { }

Page 77: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics • //A Library containing only Books

Library myBooks = new Library(); ... Book lastBook = (Book) myBooks.retrieveLast();

• public class Library<E> { private List resources = new ArrayList<E>(); public void addMedia(E x) { resources.add(x); } public E retrieveLast() {

int size = resources.size(); if (size > 0) { return resources.get(size - 1); } return null; } }

• Library<Book> myBooks = new Library<Book>(); ... Book lastBook = myBooks.retrieveLast();

• myBooks.addMedia(myFavoriteBook); // could generate error if // the input “myFavoriteBook” is not of Book type.

Page 78: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics

• Note: When compiling code that refers to generics, you might encounter a message like this: – Note: MyFile.java uses unchecked or unsafe

operations. – Note: Recompile with -Xlint:unchecked for

details.

• This error means that you have bypassed generics and have lost the benefit of compile-time type checking. You should fix your code to make full use of generics and take advantage of compile-time type checking.

Page 79: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using generic types

• You'll usually see generics when dealing with collections of some kind

• When you specify the type of object stored in a collection: – The compiler can verify any operation that adds

an object to the collection. – The type of an object retrieved from a

collection is known, so there's no need to cast it to a type.

Page 80: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using generic types• Type Parameter Conventions: a type parameter is a single,

uppercase letter — this allows easy identification and distinguishes a type parameter from a class name. – <T> — Type

– <S> — for Type, when T is already in use

– <E> — Element (used extensively by the Java Collections Framework)

– <K> — Key

– <V> — Value

– <N> — Number

• You can invoke a generic type with any class, but you cannot invoke a generic type with a primitive type, such as int

Page 81: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics and relationships between types

• List<String> ss = new ArrayList<String>(1); List<Object> os = ss; //WRONG. This causes a compile error.

• But suppose that the above assignment was allowed and you then added an object to os: os.add(new Object());

• If you later tried to retrieve the object from ss: ss.get(0);

• the Object that is returned isn't guaranteed to be a String — this clearly violates how ss was defined

Page 82: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics and type erasure• When a generic type is instantiated, the compiler

translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method

• Type erasure means that Java applications that use generics maintain binary compatibility with Java libraries and applications created before generics

• Iterator<String> is translated to type Iterator, which is called the raw type — a raw type is a class without a type argument. This means that you can't find out what type of Object a generic class is using at runtime

Page 83: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Generics and type erasure• public class MyClass<E> {

public static void myMethod(Object item) { if (item instanceof E) { //Compiler error ... } E item2 = new E(); //Compiler error E iArray[] = new E[10]; //Compiler error E obj = (E)new Object(); //Unchecked cast

warning } }

• The operations shown in red are meaningless at runtime because the compiler removes all information about the actual type argument (represented by the type param E) at compile-time.

• Type erasure exists so that new code may continue to interface with legacy code, but it should not otherwise be considered good programming practice

Page 84: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Wildcard types• reverse(List<?> list)• The question mark is called the wildcard type. A wildcard

represents some type, but one that is not known at compile time. In this case, it means that the reverse method can accept a List of any type. It might be a List of Integer, for example, or of String

• List<?> is NOT the same as List<Object>• Constrained with a lower bound

In "List<? super Number>" the List must contain either Numbers or Objects

• Constrained with an upper bound In "List<? extends Number>" the List must contain Numbers, Integers, Longs, Floats or one of the other subtypes of Number

Page 85: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Using generic methods• A generic method defines one or more type parameters in the

method signature, before the return type:

static <T> void fill(List<? extends T> list, T obj) • A type parameter is used to express dependencies

between: – the types of the method's arguments – the type of the method's argument and the method's return

type

• The type parameters are inferred from the invocation context, as in this example that calls the fill method: public static void main(String[] args) {

List<String> list = new ArrayList<String>(10); for (int i = 0; i < 10; i++) { list.add(""); } String filler = args[0]; Collections.fill(list, filler); ... }

Page 86: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 87: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Interfaces• An interface defines a protocol of behavior that can be

implemented by any class anywhere in the class hierarchy; it defines a set of methods but does not implement them.

• A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior

• An interface is different from abstract class:– An interface cannot implement any methods, whereas an abstract

class can.

– A class can implement many interfaces but can have only one super-class.

– An interface is not part of the class hierarchy.

– Unrelated classes can implement the same interface

Page 88: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Interfaces • All methods declared in an interface are implicitly

public and abstract.

• An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final.

• Member declarations in an interface prohibit the use of some declarations; you cannot use transient, volatile, or synchronized in a member declaration in an interface. Also, you cannot use the private and protected specifiers when declaring members of an interface.

Page 89: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Package • A package is a collection of related types providing access

protection and name space management. Note that types refers to classes, interfaces, enums, and annotations

• You should bundle these classes and the interface in a package for several reasons, including the following:– You and other programmers can easily determine that these types

are related.

– You and other programmers know where to find types that can provide graphics-related functions.

– The names of your types won't conflict with the type names in other packages because the package creates a new namespace.

– You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the the package

Page 90: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Package naming• By Convention:  Companies use their reversed Internet

domain name in their package names (for example, com.company.package).

• Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.company.region.package).

• In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int".

• In this event, the suggested convention is to use an underscore.

Page 91: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Java language

• Object-Oriented Programming Concepts• Language basics• Object basics and simple data objects• Classes and inheritance• Interfaces and packages• Common problems/solutions

Page 92: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Common problems• Problem: The compiler complains that it can't find a class.

– Make sure you've imported the class or its package.

– Unset the CLASSPATH environment variable, if it's set.

– Make sure you're spelling the class name exactly the same way as it is declared. Case matters!

– If your classes are in packages, make sure that they appear in the correct subdirectory

– Also, some programmers use different names for the class name from the .java filename. Make sure you're using the class name and not the filename. In fact, make the names the same and you won't run into this problem for this reason.

Page 93: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Common problems

• Problem: The interpreter says it can't find one of my classes. – Make sure you specified the class name--not the class

file name--to the interpreter. – Unset the CLASSPATH environment variable, if it's

set. – If your classes are in packages, make sure that they

appear in the correct subdirectory– Make sure you're invoking the interpreter from the

directory in which the .class file is located

Page 94: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

Common problems• The following is a list of common programming

mistakes by novice Java programmers. – Did you forget to use break after each case statement

in a switch statement? – Did you use the assignment operator = when you really

wanted to use the comparison operator ==? – Are the termination conditions on your loops correct?

Make sure you're not terminating loops one iteration too early or too late. That is, make sure you are using < or <= and > or >= as appropriate for your situation.

– Remember that array indices begin at 0, so iterating over an array looks like this:

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

Page 95: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

• Are you comparing floating-point numbers using ==? Remember that floats are approximations of the real thing. The greater than and less than (> and <) operators are more appropriate on floating-point numbers.

• Make sure that blocks of statements are enclosed in curly brackets { }. The following code looks right because of indentation, but it doesn't do what the indents imply because the brackets are missing:

for (int i = 0; i < arrayOfInts.length; i++) arrayOfInts[i] = i; System.out.println("[i] = " +

arrayOfInts[i]); • Are you using the correct conditional operator? Make sure

you understand && and || and are using them appropriately. • Do you use the negation operator ! Try to express condition

without it. Doing so is less confusing and error-prone.

Page 96: Introduction to Java. Java characteristics Object-oriented Distributed Platform independent Secure Strongly typed

• Are you using a do-while? If so, do you know that a do-while executes at least once, but a similar while loop may not be executed at all?

• Are you trying to change the value of an argument from a method? Arguments in Java are passed by value and can't be changed in a method.

• Did you inadvertently add an extra semicolon (;), thereby terminating a statement prematurely? Notice the extra semicolon at the end of this for statement:

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

arrayOfInts[i] = i;