Download Java Introduction

Document related concepts
no text concepts found
Transcript
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
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
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
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
Java runtime architecture
Java source code
Java compiler
Platform
independent
Java byte code
byte code
interpreter
CPU
JVM
Platform
dependent
byte code
compiler
Java CPU
native
machine code
CPU
Java machine
JVM
Java byte code
•
•
•
•
•
•
•
•
Byte code format
opcode (1-byte)
pc program counter
operand1
operand2
optop top of stack
…
vars local variables
frame execution environment
Garbage-collected heap
RISC like instruction set, 32-bit register
Stack-based architecture
JVM instruction functions
•
•
•
•
•
•
Stack manipulation
Array management
Arithmetic/logical operations
Method invocation/return
Exception handling
Thread synchronization
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
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
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.
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
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);
}
}
Language basics
•
•
•
•
Variables
Operators
Expressions, statements, and blocks
Control flow statements
Variables
• Definition: A variable is an item of data
named by an identifier
• Data Types
• Variable Names
• Scope
• Variable Initialization
• Final Variables
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
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)
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
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
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;
Language basics
•
•
•
•
Variables
Operators
Expressions, statements, and blocks
Control flow statements
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)
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
Control flow statements
Statement Type
looping
decision making
exception handling
Branching
Keyword
while, do-while, for
if-else, switch-case
try-catch-finally, throw
break, continue, label:,
return
• control flow statement details {
statement(s)
}
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
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
Creating objects
Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100,
200);
Rectangle rectTwo = new Rectangle(50, 100);
1.declaration
2.instantiation
3.initialization
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();
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
Simple data objects
• Characters and strings
• Numbers
• Arrays
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.
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))) { ... }
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());
}}
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);
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
Simple data objects
• Characters and strings
• Numbers
• Arrays
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.
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
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
Writing classes
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
(Optional) Interfaces implemented by the class
Interfaces
{ ClassBody }
Provides the class's functionality
Declaring member variables
• private List<Object> items;
• Element
• accessLevel
variable
Function
(optional) Access level for the
– public, protected, private, and default
• static
• final
change
• transient
(optional) Declares a class variable
(optional) variable value cannot
(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
Declaring methods
• Element
• @annotation
data)
• accessLevel
• static
• <TypeVariables>
• abstract
• final
• native
Function
(Optional) An annotation (sometimes called meta-
(Optional) Access level for the method
(Optional) Declares a class method
(Optional) Comma-separated list of type variables
(Optional) Indicates that the method must be implemented in
concrete subclasses
(Optional) Indicates that the method cannot be overridden
(Optional) Indicates that the method is implemented in
another language
(Optional) Guarantees exclusive access to this
• synchronized
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
Providing constructors
• public Stack() {
items = new ArrayList<Object>();
}
• public Stack(int size) {
items = new ArrayList<Object>(size);
}
• public, private, protected, default
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
Manage inheritance
All Classes are Descendants of Object
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
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
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
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
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); } }
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)
}
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
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
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
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() { ... }
}
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
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
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
• 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() { ... }
}}
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() { ... }
};
}
}
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();
}
}
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
Types of Nested Classes
• Type
Scope
Inner
•
•
•
•
member
member
local
where it is defined
no
yes
yes
yes
static nested class
inner [non-static] class
local class
anonymous class
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
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
• 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(); }
• 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
…
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
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
Annotations
• @Author("MyName")
class myClass() { }
or
@SuppressWarnings("unchecked")
void MyMethod() { }
• there are three built-in annotations:
– @Deprecated,
– @Override, and
– @SuppressWarnings
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 } }
Classes and inheritance
•
•
•
•
•
•
Writing classes
Manage inheritance
Nested classes
Enumerated types
Annotations
Generics
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 { }
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.
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 compiletime type checking.
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.
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
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
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
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
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
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(""); }
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
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
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.
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
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.
Java language
•
•
•
•
•
•
Object-Oriented Programming Concepts
Language basics
Object basics and simple data objects
Classes and inheritance
Interfaces and packages
Common problems/solutions
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.
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
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++) . . .
• 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.
• 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;