Download Part 2 Slides

Document related concepts
no text concepts found
Transcript
Think Java:
Java Programming
Language Part 2
Chia James Chang
[email protected]
(Materials are based on: The Java
Tutorials)
Overview
• The Java Tutorials: Learning the Java Language
http://docs.oracle.com/javase/tutorial/index.html
•
•
•
•
•
•
Quick Review (Language Basics, Classes, Objects)
Interfaces
Numbers and Strings
Generics
Packages
What’s Next?
References
• The Java Tutorials
http://docs.oracle.com/javase/tutorial/index.html
• Java SE 7 JDK (Windows, Unix/Linux, and Mac)
http://www.oracle.com/technetwork/java/javase/downloads/index.html
• Java Platform SE 7 Documentation
http://docs.oracle.com/javase/7/docs/
• Eclipse IDE for Java EE Developers
http://www.eclipse.org/downloads/
• Java Language Specification
http://docs.oracle.com/javase/specs/
• Java SE API
http://www.oracle.com/technetwork/java/javase/documentation/api-jsp136079.html
Reading Materials
• All materials are based on The Java Tutorials
http://docs.oracle.com/javase/tutorial/index.html
• Interfaces
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
• Numbers and Strings
http://docs.oracle.com/javase/tutorial/java/data/index.html
• Generics
http://docs.oracle.com/javase/tutorial/java/generics/index.html
• Packages
http://docs.oracle.com/javase/tutorial/java/package/index.html
Quick Review
(Language Basics, Classes, Objects)
Language Basics
•
•
•
•
•
•
•
Java Reserved Words
Variables
Operators
Expressions
Statements
Blocks
Control Flow Statements
Java Reserved Words
abstract assert
boolean break byte
case catch char class const continue
default do double
else enum extends
false final finally float for
goto
if implements import in instanceof int
interface
long
native new null
package private protected public
return
short static strictfp super switch synchronized
this throw throws transient try true
void volatile
while
Variables
• Instance Variables (Non-Static Fields)
int speed = 0;
• Class Variables (Static Fields)
static int numGears = 6;
• Local Variables (used in method)
int count = 0;
• Parameters (used in method)
public static void main(String[] args)
Naming
• Variable names are case-sensitive.
• The name must not be a keyword or reserved
word.
• One word
 all lowercase letters (e.g. ratio)
• Multiple words
 capitalize the first letter of each subsequent word,
aka, Camel Case (e.g. currentGear)
• Constant value
 capitalizing every letter and separating subsequent
words with the underscore character (e.g. static
final int NUM_GEARS = 6)
Primitive Data Types
data type
size
default
byte
8-bit signed
0
short
16-bit signed
0
int
32-bit signed
0
long
64-bit signed
0L
float
32-bit signed (single-precision)
0.0f
double
64-bit IEEE 754 (double-precision)
0.0d
boolean
true and false
false
char
16-bit Unicode char
‘\u0000’
Operators
Operators
Precedence
Postfix
expr++ expr--
Unary
++expr –expr +expr –expr ~ !
Multiplicative
*/%
Additive
+-
Shift
<< >> >>>
Relational
< > <= >= instanceof
Equality
== !=
Bitwise AND
&
Bitwise exclusive OR
^
Bitwise inclusive OR
|
Operators
Operators
Precedence
Logical AND
&&
Logical OR
||
Tenary
?:
Assignment
= += -= *= /= %= &= ^= |= <<= >>=
>>>=
Expressions
An expression is a construct made up of
variables, operators, and method invocations.
int result = 1 + 2;
The data type of the value returned by an
expression depends on the elements used in
the expression.
String helloWorld = “hello” + “world”;
You can specify exactly how an expression will
be evaluated using ( and ).
int result = (x + y) / 100;
Statements
• A statement forms a complete unit of
execution terminated with a semicolon (;).
• Expression statements
 Assignment expression: speed = 0;
 Method invocations: System.out.println(“hello”);
 Object creation expressions
Point originOne = new Point(23, 94);
• Declaration statements
int speed = 0;
• Control flow statements
if (x > y) { ... }
Blocks
• A block is a group of zero or more
statements between balanced braces and
can be used anywhere a single statement is
allowed.
if (x > 1) {
System.out.println(“true.”);
} else {
System.out.println(“false.”);
}
Control Flow Statements
•
•
•
•
•
•
•
•
•
if
switch
while
do
for
break
continue
return
try/throw
Object-Oriented
Programming (OOP)
Object-Oriented Programming
(OOP)
•
•
•
•
•
•
Classes
Objects
Inheritance
Interfaces
Abstract Classes
Packages
Object-Oriented Programming (OOP)
• A fundamental principle of object-oriented
programming:
 Encapsulation
 Inheritance
 Polymorphism
Classes
• A class is a blueprint or prototype from
which objects are created.
 Class header
 Class body
class MyClass extends MySuperClass
implements YourInterface{
// fields (variables)
// constructors
// methods
}
Objects
• An object is a software bundle of related
behavior (methods) and state (fields).
• Referencing an object’s fields.
objectReference.fieldName;
bike.speed;
• Calling an object’s methods.
objectReference.methodName(argumentList);
bike.setSpeed(10);
Creating Objects
• A class provides the blueprint for objects;
you create an object from a class.
Point originalOne = new Point(23, 40);
• The above statement has three parts:
 Declaration: variable declarations
 Instantiation: the new keyword operator creates
the object.
 Initialization: the constructor initializes the new
object.
Garbage Collector
• Garbage collector: The Java VM deletes
objects when it determines that they are no
longer being used.
• An object is eligible for garbage collection
when there are no more references to that
object. Or, you can explicitly drop an object
reference by setting the variable to null.
Nested Classes
Classes
• Classes declared outside of any class are known as
top-level classes.
• Classes declared as members of other classes are
called as nested classes.
Nested Classes
• There are two kinds of nested classes:
 Static member class: declared static
 Inner class: non-static member class, anonymous class and local
class
class OuterClass {
static class StaticNestedClass {
…
}
class InnerClass {
…
}
}
Static Member Classes
• Static member class is a static member of an
enclosing class.
• Although enclosed, it does not have an enclosing
instance of that class, and cannot access the
enclosing class’s instance fields and call its instance
methods.
• It can access or call static members of the enclosing
class, even those members that are declared
private.
Non-Static Member Classes
• A non-static member class is a non-static member
of an enclosing class.
• Each instance of the non-static member class’s
instance methods can call instance method in the
enclosing class and access the enclosing class
instance’s non-static fields.
Anonymous Classes
• An anonymous class is a class without a name.
• It is not a member of it’s enclosing class.
• Instead, an anonymous class is simultaneously
declared and instantiated any place where it is legal
to specify an expression.
Local Class
• A local class is a class that is declared anywhere
that a local variable is declared.
• It has the same scope as a local variable.
• A local class instance can access the surrounding
scope’s local variables and parameters.
• However, the local variable and parameters that are
accessed must be declared final.
Why Use Nested Classes?
• It’s a way of logically grouping classes that are only
used in one place. Nesting such “helper classes”
makes their package more streamlined.
• It increases encapsulation.
class OuterClassA {
private int aVar;
class InnerClassB {
private int bMethod() {
return aVar;
}
}
}
Why Use Nested Classes?
• Nested classes can lead to more readable and
maintainable code.
class OuterClassA {
private int aVar;
class InnerClassB {
private int bMethod() {
return aVar;
}
}
}
Question
• The following program doesn’t compile:
public class Problem {
String s;
static class Inner {
void testMethod() {
s = "Set from Inner";
}
}
}
• What do you need to do to make it compile?
Answer
• Delete static in front of the declaration of the Inner
class. An static inner class does not have access to
the instance fields of the outer class.
Enum Types
• The constructor for an enum type must be
package-private access. It automatically creates the
constants that are defined at the beginning of the
enum body. You cannot invoke an enum
constructor yourself.
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Enum Types
• An enum type is a type whose fields consist of a
fixed set of constants.
• The enum declaration defines a class (called an
enum type). The enum class body can include
methods and other fields. The compiler
automatically adds some special methods, e.g.
values method, when it creates an enum.
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Annotations
• Provide data about a program that is not part of
the program itself.
• Apply to program’s declarations of classes, fields,
methods, and other program elements.
• Appear first and may include elements with named
or unnamed values.
@SuppressWarnings(value = “unchecked”)
@SuppressWarnings(“unchecked”)
@Override
@Deprecated
Defining Annotation Type
import java.lang.annotation.*;
@Documented
@interface ClassPreamble {
String author();
}
@ClassPreamble (
author = "John Doe"
}
Public class MyClass {
}
Interfaces
Interfaces
• An interface is a contract between a class and the
outside world.
• When a class implements an interface, it promises
to provide the behavior published by that interface.
• An interface is not a class.
• Writing an interface is similar to writing to a class,
but they are two difference concepts:
 A class describes the attributes and behaviors of an
object.
 An interface contains behaviors that a class implement.
Interfaces vs Classes
• An interface is not a class.
• Writing an interface is similar to writing to a class,
but they are two difference concepts:
 A class describes the attributes and behaviors of an
object.
 An interface contains behaviors that a class implement.
Interfaces and Classes: Similarities
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension,
with the name of the interface matching the name
of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their
corresponding bytecode file must be in a directory
structure that matches the package name.
Interfaces and Classes: Differences
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields.
• The only fields that can appear in an interface must
be declared both static and final – constant.
• An interface is not extended by a class; it is
implemented by a class.
• An interface can extend multiple interfaces.
Interfaces
• Interface can contain only constants, method
signatures, and nested types. There are no method
bodies.
• All methods declared in an interface are implicitly
public.
• All constants defined in an interface are implicitly
public, static, and final.
• An interface declaration consists of modifiers, the
keyword interface, the interface name, a commaseparated list of parent interfaces (if any), and the
interface body.
Define Interface
public interface Bicycle {
// constant
int MAX_GEARS = 20;
//
wheel revolutions per minute
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
void changeCadence(int newValue);
}
Implements Interface
public interface Bicycle {
//
wheel revolutions per minute
void changeGear(int newValue);
. . .
}
class MountainBike implements Bicycle {
void changeGear(int newValue)
gear = newValue;
}
Bicycle
. . .
}
Mountain
Bike
Road Bike
Tandem
Bike
Rewriting Interfaces
• Developed An Interface
Public interface DoIt {
void doSomething(int i);
}
• Want to Add A Method
Public interface DoIt {
void doSomething(int i);
int doSomethingElse(String s);
}
• Add A Method
Public interface DoItPlus extends DoIt {
boolean doSomethingElse(String s);
}
Interfaces & Multiple Inheritance
• The Java programming language does not permit
multiple inheritance, but interfaces provide an
alternative.
• In Java, a class can inherit from only one class but it
can implement more than one interface. Therefore,
objects can have multiple types: the type of their
own class and the types of all the interfaces that
they implement. This means that if a variable is
declared to be the type of an interface, its value can
reference any object that is instantiated from any
class that implements the interface.
Multiple Interface
public interface GroupedInterface extends
Interface1, Interface2, Interface3 {
// constant declarations
// base of natural logarithms
double E = 2.718282;
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
Summary of Interfaces
• A protocol of communication between two
objects
• Contains signatures and constant but not
method implementation
• A class implements an interface must
implement all methods
• An interface name can be used anywhere a
type can be used
Question 1
• What’s wrong with the following interface?
Public interface SomethingWrong {
void aMethod(int aValue) {
System.out.println(“Hi Mom”
}
}
Answer 1
• It has a method implementation in it. It should just
have a declaration.
public interface SomethingWrong {
void aMethod(int aValue);
}
Question 2
• Is the following interface valid?
Public interface Marker {
}
Answer 2
• Yes. Methods are not required.
Abstract Classes
Abstract Classes and Methods
• An abstract class is a class that is declared
abstract—it may or may not include abstract
methods. Abstract classes cannot be instantiated,
but they can be subclassed.
• An abstract method is a method that is declared
without an implementation (without braces, and
followed by a semicolon).
abstract void moveTo(double x, double y);
Abstract Classes and Methods
• If a class includes abstract methods, the class itself
must be declared abstract.
public abstract class GraphicObject {
abstract void draw();
}
• An abstract class may have static fields and static
methods. You can use these static members with a
class reference as you would with any other class.
AbstractClass.staticMethod();
Interfaces vs Abstract Classes
• An interface is a reference type, similar to a class,
that can contain only constants, method signatures,
and nested types. There are no method bodies.
Interfaces cannot be instantiated—they can only be
implemented by classes or extended by other
interfaces.
• Unlike interfaces, abstract classes can contain fields
that are not static and final, and they can contain
implemented methods.
Interfaces vs Abstract Classes
public interface GraphicObject {
int MIN_SIZE = 10;
void moveTo(int newX, int newY);
void draw();
}
class Circle implements GraphicObject {
void moveTo(int newX, int newY) {
. . .
}
void draw() {. . .}
}
Interfaces vs Abstract Classes
abstract class GraphicObject {
int MIN_SIZE = 10;
int x, y;
void moveTo(int newX, int newY) {
. . .
}
abstract void draw();
}
class Circle extends GraphicObject {
void draw() {. . .}
}
Abstract Class Implements Interface
• A class that implements an interface must
implement all of the interface’s methods.
• An abstract class does not need to implement all of
the interface methods.
abstract class X implements Y {
// implements all but one method of Y
}
class XX extends X {
// implements the remaining method in Y
}
Summary of Inheritance
• Except for the Object class, a class has exactly one
direct superclass.
• A class inherits fields and methods from all its
superclasses, whether direct or indirect.
• A subclass can override methods that it inherits, or
it can hide fields or methods that it inherits.
• The Object class is the top of the class hierarchy. All
classes are descendants from this class and inherit
methods from it.
Summary of Abstract Classes
• You can prevent a class or a method from being
subclassed by using the final keyword.
• An abstract class can only be subclassed; it cannot
be instantiated.
• An abstract class can contain abstract methodsmethods that are declared but not implemented.
Subclasses then provide the implementations for
the abstract methods.
Question
public class ClassA {
public void methodOne(int i) {}
public void methodTwo(int i) {}
public static void methodThree(int i) {}
public static void methodFour(int i) {}
}
public class ClassB extends ClassA {
public static void methodOne(int i) {}
public void methodTwo(int i) {}
public void methodThree(int i) {}
public static void methodFour(int i) {}
}
• What method overrides a method in the superclass?
Answer
Question 1a: Which method overrides a method in
the superclass?
Answer 1a: methodTwo
Question 1b: Which method hides a method in the
superclass?
Answer 1b: methodFour
Question 1c: What do the other methods do?
Answer 1c: They cause compile-time errors.
Numbers & Strings
Numbers Classes
• When working with numbers, most of the
time you use the primitive types such as int,
float, byte, etc. in your code.
• The Java platform provides wrapper classes
for each of the primitive data types. These
classes “wrap” the primitive in an object.
Boxing and Unboxing
• Often, the wrapping is done by the compiler:
 If you use a primitive where an object is expected, the
compiler boxes the primitive in its wrapper class for you.
 If you use a number object when a primitive is expected,
the compiler unboxes the object for you.
Integer x, y;
x = 12; // boxed
y = 15; // boxed
System.out.println(x+y); // unboxed
Number Wrapper Classes
Number
Double
Byte
Integer
Float
Short
Long
Why Use Number Object?
• As an argument of a method that expects an object
(often used when manipulating collections of
numbers).
• To use constants defined by the class, such as
MIN_VALUE and MAX_VALUE, that provide the
upper and lower bounds of the data type.
• To use class methods for converting values to and
from primitive types, strings, and between number
systems (decimal, octal, hexadecimal, binary).
Strings
• Strings, which are widely used in Java, are a
sequence of characters and objects.
• Creating Strings
String greeting = “Hello world!”;
String hello = new String(“Hello world!”);
• The String class is immutable, so that once it
is created a String object cannot be changed.
Concatenating Strings
• String class includes a concat() method
String1.concat(string2);
• Use Concat() method with sting literals
“My name is “.concat(“John.”);
• More commonly concatenated with “+” operator
“Hello, “ + “world” + “!”;
Creating Format Strings
• Use printf() and format() to print output
System.out.printf(“%f, %d”, floatV, intV);
• String class includes a format() method
String fs;
fs = String.format(“%f, %d”, floatV, intV);
System.out.println(fs);
Converting Strings to Numbers
• Use valueOf() of Number subclasses
oByte, Integer, Double, Float, Long, and Short
String abc = “12.3”;
float a = (Float.valueOf(abc)).floatValue();
Converting Numbers to Strings
• Concatenate “i” with an empty string
int i = 5;
String s1 = “” + i;
• Use toString() of Number subclasses
int i;
String s2 = Integer.toString();
More Methods in String
• More methods in String class
• charAt(…)
• substring(…)
• split(…)
• trim()
• toLowerCase(), toUpperCase()
• indexOf(…)
• contains(…)
• …
StringBuilder Class
• StringBuilder objects are like String objects, except
that they can be modified.
• length()
• capacity() // number of char spaces allocated
• append()
• insert()
• delete()
• replace()
• reverse()
• toString()
Questions
• What is the initial capacity of the following
string builder? (Hints: string length = 26)
StringBuilder sb =
new StringBuilder("Able was I ere I saw Elba.");
Answers
• Initial string length + 16 = 26 + 16 = 42.
Generics
Why Use Generics?
• Generics enable types (classes and interfaces)
to be parameters when defining classes,
interfaces and methods.
• A generic type is a generic class or interface
that is parameterized over types.
• Type parameters provide a way for you to
re-use the same code with different inputs.
Why Use Generics? (continued)
• Strong type checks at compile time. A Java
compiler applies strong type checking to
generic code.
• Enabling programmers to implement generic
algorithms (different types, type safe, and
easier to read.)
Why Use Generics? (continued)
• Elimination of casts.
// Without generics
List list = new ArrayList();
list.add(“hello”);
String s = (String) list.get(0);
// With generics
List<String> list = new ArrayList<String>();
list.add(“hello”);
String s = list.get(0);
Generics
• Non-Generic version of Box class:
public class Box {
private Object obj;
public void add(Object obj) {
this.obj = obj;
}
public Object get() {
return obj;
}
}
Generics (continued)
• Non-Generic version of Box class:
public class BoxDemo1 {
public static void main(String[] args) {
// ONLY place Integer objects into this
box!
Box intBox = new Box();
intBox.add(new Integer(10));
Integer someInt = (Integer)intBox.get();
System.out.println(someInt);
}
}
Generics (continued)
• Without Generics – runtime ClassCastException
public class BoxDemo2 {
public static void main(String[] args) {
// ONLY place Integer objects into this
box!
Box intBox = new Box();
intBox.add(“10”);
Integer someInt = (Integer)intBox.get();
System.out.println(someInt);
}
}
Generic Class
• A generic class is defined with the following format:
class ClassName<T1, T2, …, Tn> { }
• class name
• type parameters (also called type variables) T1, …
• type parameter can be any non-primitive type:
 class type
 interface type
 array type
 another type variable
Generic Types
• Generic version of Box class.
public class Box<T> {
private T t; // T stands for “Type”
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
Generic Types
• Multiple type parameters (each parameter must be
unique within its declaring class or interface)
Box<T, U>
• Generic type innovation replaces T with some
concrete type
Box<Integer> intBox = new Box<Integer>();
intBox.add(new Integer(10));
Integer someInt = intBox.get();
intBox.set(“10”); // compilation error
Type Parameter Naming
Conventions
• By convention, type parameter names are single,
uppercase letters.
 E – Element (used extensively by the Java Collections
Framework)
 K – Key
 N – Number
 T – Type
 V – Value
 S, U, V etc. – 2nd, 3rd, 4th types
Type Inference
• Determines the type argument(s) that make the
invocation applicable using the method invocation
and corresponding declaration.
• Determines the types of the arguments and the
return types.
• Finds the most specific type that works with all of
the arguments.
static <T> pick(T t1, T t2) { return t2; }
Serializable s = pick(“a”, new
ArrayList<String>());
Type Inference
• Define a static generic method
public static <U> void addBox(U u,List<Box<U>>
boxes) {
Box<U> box = new Box<U>();
box.add(u);
boxes.set(box);
}
• Use the method (with type inference)
BoxDemo.<Integer>setBox(Integer.valueOf(10),
listOfIntBoxes);
// type inference: let compiler infer the type
BoxDemo.addBox(Integer.valueOf(20),listOfIntBoxes);
Bounded Type Parameters
• Bounded type parameter restricts the kind of types
that are allowed to be passed to a type parameter
• To declare a bounded type parameter:
 list the type parameter’s name
 followed by the extends keyword
 followed by its upper bound
public <U extends Number> void inspect(U u) {
System.out.println(“T: “ + t.getClass().getName());
System.out.println(“U: “ + u.getClass().getName());
}
The Need for Wildcards
• Circle is a kind of (or subtype) Shape.
• String is a kind of Object.
• List<Object> is a kind of Collection<Object>.
• BUT, List<String> is NOT a kind of List<Object>.
 Polymorphic behavior does not apply to multiple
parameterized types the differ only in regard to
one type parameter being a subtype of another
type parameter.
Wildcards
• In generics, an unknown type is represented by the
wildcard character “?”.
• Upper bounded wildcard
ClassName<? extends UpperBoundedClassName>
• Lower bounded wildcard
ClassName<? super LowerBoundedClassName>
• Unbounded wildcard
ClassName<?>
Upper Bounded Wildcards
• Upper bounded wildcard (“an unknown type that is
a subtype of call”)
 e.g. Number: Integer, Double, Float, Number
ClassName<? extends UpperBoundedClassName>
List<? extends Number>
Unbounded Wildcards
• Unbounded wildcard: list of unknow type
<?> OR <? extends Object>
// List<Object>,List<Integer>,List<String>,List<Double>
public static void printList(List<Object> list) {
for (Object e : list)
System.out.println(e + “ “);
System.out.println();
//
public static void printList(List<?> list) {
for (Object e : list)
System.out.println(e + “ “);
System.out.println();
Lower Bounded Wildcards
• Lower bounded wildcard (“an unknown type that is
a super type of call”)
• e.g. Integer: Integer, Number, Object
ClassName<? super LowerBoundedClassName>
List<? super Integer>
public static void addNumbers(List<? super
Integer> list) {
for (int i = 1; i <= 10; i++) {
list.add(i);
}
}
Type Erasure
• Type erasure: a process where the compiler
removes all information related to type parameters
and type arguments within a class or method.
• Type erasure enables Java applications that use
generics to maintain binary compatibility with Java
libraries and applications that were created before
generics.
• For instance, Box<String> is translated to type Box,
which is called the raw type.
Question 1
• What can you do with it?
public class AnimalHouse<E> {
private E animal;
public void sendAnimal(E x) { animal = x; }
public E getAnimal() { return animal; }
}
public class Animal {}
public class Cat extends Animal {}
public class Dog extends Animal {}
AnimalHouse<Animal> house = new AnimalHouse<Cat>();
Answer 1
• Failed to compile. AnimalHouse<Cat> and
AnimalHouse<Animal> are not compatible types,
even though Cat is a subtype of Animal.
Question 2
• What can you do with it?
public class AnimalHouse<E> {
private E animal;
public void sendAnimal(E x) { animal = x; }
public E getAnimal() { return animal; }
}
public class Animal {}
public class Cat extends Animal {}
public class Dog extends Animal {}
AnimalHouse<Cat> house = new AnimalHouse<Animal>();
Answer 2
• Failed to compile. AnimalHouse<Cat> and
AnimalHouse<Animal> are not compatible types,
even though Cat is a subtype of Animal.
Question 3
• What can you do with it?
public class AnimalHouse<E> {
private E animal;
public void sendAnimal(E x) { animal = x; }
public E getAnimal() { return animal; }
}
public class Animal {}
public class Cat extends Animal {}
public class Dog extends Animal {}
AnimalHouse<?> house = new AnimalHouse<Cat>();
house.setAnimal(new Cat());
Answer 3
• Failed to compile.
 The first line is acceptable. It’s OK to define an instance
of unknown type.
 However, the compiler doesn’t know the type of animal
stored in house so the setAnimal method cannot be
used.
Question 4
• What can you do with it?
public class AnimalHouse<E> {
private E animal;
public void sendAnimal(E x) { animal = x; }
public E getAnimal() { return animal; }
}
public class Animal {}
public class Cat extends Animal {}
public class Dog extends Animal {}
AnimalHouse house = new AnimalHouse ();
house.setAnimal(new Dog());
Answer 4
• Compiles with a warning.
• The compiler doesn’t know what type house
contains. It will accept the code, but warn that there
might be a problem when setting the animal to an
instance of Dog.
Packages
Packages
• A package is a grouping of related types providing
access protection and name space management.
• Placing your code into packages makes large
software projects easier to manage.
Creating a Package
• To create a package,
 Choose a name for the package
 Put a package statement at the top of every source file
 The package statement must be the first line in the
source file
 There can be only one package statement in each source
file, and it applies to all types in the file.
package graphics;
public abstract class Graphic {
}
Naming a Package
• Package names are written in all lower case
• Packages in the Java language itself begin with java
or javax
• Companies use their reversed Internet domain
name, e.g., com.acme.mypackage
• In some cases, the Internet domain name may not
be a valid package name. The suggested
convention is to add an underscore.
• Domain name: hyphenated-name.example.org
• Package name: org.example.hyphenated_name
Using Package Members
• To use a public package member from outside its
package, you must do one of the following:
 Refer to the member by its fully qualified name
 Import the package member
 Import the member’s entire package
Referring By Its Qualified Name
• Use the member’s fully qualified name from a
different package
package graphics;
public class Rectangle() {}
package othersomePackage;
graphics.Rectangle myRect =
new graphics.Rectangle();
Importing a Package Member
• To import a specific member into the current file,
put an import statement at the beginning of a file
before any type definitions but after the package
statement.
package otherPackage;
import graphics.Rectangle;
Rectangle myRect = new Rectangle();
Importing an Entire Package
• To import all the types contained in a particular
package, use the import statement with the asterist
(*) wildcard character.
package otherPackage;
import graphics.*;
Rectangle myRect = new Rectangle();
Circle myCircle = new Circle();
Packages Imported Automatically
• For convenience, the Java compiler automatically
imports three entire packages for each source file:
 the package with no name
 the java.language package
 the current package (the package for the current file)
Packages are not Hierarchical
• At first, packages appear to be hierarchical, but
they are not.
• The prefix java.awt is used for a number of related
packages to make the relationship evident, but not
to show inclusion.
• You must import both packages with all their files:
java.awt.*
java.awt.color.*;
Name Ambiguities
• If a member in one package shares its name with a
member in another package and both packages
are imported, you must refer to each member by
its qualified name.
 For instance, Rectangle class in both graphics and
java.awt packages:
import java.awt.*
import graphics.*;
graphics.Rectangle myRect;
Static Import Statement
• The static import statement gives you a way to
import the constants and static methods of a class
without needing to prefix the name of their class.
• Use properly, static import makes code more
readable by removing class name repetition.
java.lang.Math:
public static final double PI = 3.14159;
double r = Math.cos(Math.PI * theta);
import static java.lang.Math.PI;
double r = cos(PI * theta);
Managing Source and Class Files
• Put the source code for a class, interface,
enumeration, or annotation type in a text file whose
name is the simple name of the type and whose
extension is .java.
//Rectangle.java
package com.acme.graphics;
public class Rectangle {}
• Put the source file in a directory whose name
reflects the name of the package.
c:\src\com\acme\graphics\Rectangle.java
Managing Source and Class Files
• The compiled .class file should be arranged in
different directory.
c:\classes\com\acme\graphics\Rectangle.class
• The full path to the classes directory is called the
class path and is set with the CLASSPATH system
variable.
• A class path may include several paths, separated
by a semicolon (Windows) or colon (Unix).
CLASSPATH=c:\classes;c:\Users\james\classes
Questions 1
• Assume that you have written some classes.
Belatedly, you decide that they should be split into
three packages, as listed in the table below.
• What line of code will you need to add to each
source file to put each class in the right package?
Package Name
Class Name
mygame.server
Server
mygame.shared
Utilities
mygame.client
Client
Answer 1
• The first line of each source file must specify the
package:
• In Client.java add:
package mygame.client;
• In Server.java add:
package mygame.server;
• In Utilities.java add:
package mygame.shared;
Questions 2
• Assume that you have written some classes.
Belatedly, you decide that they should be split into
three packages, as listed in the table below.
• What subdirectories must you create? Which
subdirectory does each source file go in?
Package Name
Class Name
mygame.server
Server
mygame.shared
Utilities
mygame.client
Client
Answer 2
• Within the mygame directory:
• In mygame/client/ place:
Client.java
• In mygame/server/ place:
Server.java
• In mygame/shared/ place:
Utilities.java
Questions 3
• Assume that you have written some classes.
Belatedly, you decide that they should be split into
three packages, as listed in the table below.
• Do you think you'll need to make any other
changes to the source files to make them compile
correctly? If so, what?
Package Name
Class Name
mygame.server
Server
mygame.shared
Utilities
mygame.client
Client
Answer 3
• Yes, you need to add import statements.
• In Client.java and Server.java add:
import mygame.shared.Utilities;
• In Server.java add:
import mygame.client.Client;
Naming Conventions
http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Naming Conventions - Classes
• Class names should be nouns in Upper CamelCase,
with the first letter of every word capitalized. Use
whole words — avoid acronyms and abbreviations
(unless the abbreviation is much more widely used
than the long form, such as URL or HTML).
class Bicycle {
}
Naming Conventions - Methods
• Methods should be verbs in lower CamelCase; that
is, with the first letter lowercase and the first letters
of subsequent words in uppercase.
public in getGear() {
}
Naming Conventions - Variables
• Local variables, instance variables, and class
variables are also written in lower CamelCase.
• Variable names should not start with underscore (_)
or dollar sign ($) characters, even though both are
allowed. Certain coding conventions state that
underscores should be used to prefix all instance
variables, for improved reading and program
understanding.
public int gear;
Naming Conventions - Variables
• Variable names should be short yet meaningful.
The choice of a variable name should be mnemonic
— that is, designed to indicate to the casual
observer the intent of its use.
• One-character variable names should be avoided
except for temporary "throwaway" variables.
Common names for temporary variables are i, j, k,
m, and n for integers; c, d, and e for characters.
public int speed;
Naming Conventions Constants
• Constants should be written in uppercase
characters separated by underscores. Constant
names may also contain digits if appropriate, but
not as the first character.
public final static int MAXIMUM_NUM_OF_SPEEDS = 10;
What’s Next?
What’s Next?
• Classes from Technology Service Group (TSG)@ROLF
http://www.techsamaritan.org/
 Future Java classes or non-Java classes such as C#, C++, JavaScript,
Objective-C, etc.
• Java Collections Framework @ Java Tutorials
http://docs.oracle.com/javase/tutorial/collections/index.html
• Essential Java Classes @ Java Tutorials
http://docs.oracle.com/javase/tutorial/essential/index.html
• Other Lessons from Java Tutorials
http://docs.oracle.com/javase/tutorial/
• Android Development
http://developer.android.com/
• Spring Framework
 the most popular app development framework for enterprise Java
http://www.springsource.org/
Thank you!
謝 謝!
Think Java:
Java Programming
Language Part 2
Chia James Chang
[email protected]