Скачать презентацию Think Java Java Programming Language Part 2 Chia Скачать презентацию Think Java Java Programming Language Part 2 Chia

6dbec3d0320a6467587978e36ec3b24f.ppt

  • Количество слайдов: 137

Think Java: Java Programming Language Part 2 Chia James Chang cjameschang@yahoo. com (Materials are Think Java: Java Programming Language Part 2 Chia James Chang [email protected] com (Materials are based on: The Java Tutorials)

Overview • The Java Tutorials: Learning the Java Language http: //docs. oracle. com/javase/tutorial/index. html 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 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/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/javase/documentation/api-jsp 136079. html

Reading Materials • All materials are based on The Java Tutorials http: //docs. oracle. 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/Iand. I/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) Quick Review (Language Basics, Classes, Objects)

Language Basics • • Java Reserved Words Variables Operators Expressions Statements Blocks Control Flow 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 Java Reserved Words abstract assert boolean break byte case catch char class const continue default do double else enum extends false finally float for goto if implements import in instanceof interface long native new null package private protected public return short static strictfp super switch synchronized this throws transient try true void volatile while

Variables • Instance Variables (Non-Static Fields) int speed = 0; • Class Variables (Static Variables • Instance Variables (Non-Static Fields) int speed = 0; • Class Variables (Static Fields) static int num. Gears = 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 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. current. Gear) • 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 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 0 L float 32 -bit signed (single-precision) 0. 0 f double 64 -bit IEEE 754 (double-precision) 0. 0 d boolean true and false char 16 -bit Unicode char ‘u 0000’

Operators Precedence Postfix expr++ expr-- Unary ++expr –expr ~ ! Multiplicative */% Additive +- Operators Precedence Postfix expr++ expr-- Unary ++expr –expr ~ ! Multiplicative */% Additive +- Shift << >> >>> Relational < > <= >= instanceof Equality == != Bitwise AND & Bitwise exclusive OR ^ Bitwise inclusive OR |

Operators Precedence Logical AND && Logical OR || Tenary ? : Assignment = += Operators Precedence Logical AND && Logical OR || Tenary ? : Assignment = += -= *= /= %= &= ^= |= <<= >>>=

Expressions An expression is a construct made up of variables, operators, and method invocations. 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 hello. World = “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 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 origin. One = 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 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 Control Flow Statements • • • if switch while do for break continue return try/throw

Object-Oriented Programming (OOP) Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) • • • Classes Objects Inheritance Interfaces Abstract Classes Packages Object-Oriented Programming (OOP) • • • Classes Objects Inheritance Interfaces Abstract Classes Packages

Object-Oriented Programming (OOP) • A fundamental principle of object-oriented programming: § Encapsulation § Inheritance 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. Classes • A class is a blueprint or prototype from which objects are created. § Class header § Class body class My. Class extends My. Super. Class implements Your. Interface{ // fields (variables) // constructors // methods }

Objects • An object is a software bundle of related behavior (methods) and state Objects • An object is a software bundle of related behavior (methods) and state (fields). • Referencing an object’s fields. object. Reference. field. Name; bike. speed; • Calling an object’s methods. object. Reference. method. Name(argument. List); bike. set. Speed(10);

Creating Objects • A class provides the blueprint for objects; you create an object Creating Objects • A class provides the blueprint for objects; you create an object from a class. Point original. One = 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 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 Nested Classes

Classes • Classes declared outside of any class are known as top-level 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: 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 Outer. Class { static class Static. Nested. Class { … } class Inner. Class { … } }

Static Member Classes • Static member class is a static member of an enclosing 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 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 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 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 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 Outer. Class. A { private int a. Var; class Inner. Class. B { private int b. Method() { return a. Var; } } }

Why Use Nested Classes? • Nested classes can lead to more readable and maintainable Why Use Nested Classes? • Nested classes can lead to more readable and maintainable code. class Outer. Class. A { private int a. Var; class Inner. Class. B { private int b. Method() { return a. Var; } } }

Question • The following program doesn’t compile: public class Problem { String s; static Question • The following program doesn’t compile: public class Problem { String s; static class Inner { void test. Method() { 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 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. 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 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 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. @Suppress. Warnings(value = “unchecked”) @Suppress. Warnings(“unchecked”) @Override @Deprecated

Defining Annotation Type import java. lang. annotation. *; @Documented @interface Class. Preamble { String Defining Annotation Type import java. lang. annotation. *; @Documented @interface Class. Preamble { String author(); } @Class. Preamble ( author = "John Doe" } Public class My. Class { }

Interfaces Interfaces

Interfaces • An interface is a contract between a class and the outside world. 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 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. § 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 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 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 Define Interface public interface Bicycle { // constant int MAX_GEARS = 20; // wheel revolutions per minute void change. Gear(int new. Value); void speed. Up(int increment); void apply. Brakes(int decrement); void change. Cadence(int new. Value); }

Implements Interface public interface Bicycle { // wheel revolutions per minute void change. Gear(int Implements Interface public interface Bicycle { // wheel revolutions per minute void change. Gear(int new. Value); . . . } class Mountain. Bike implements Bicycle { void change. Gear(int new. Value) gear = new. Value; } Bicycle . . . } Mountain Bike Road Bike Tandem Bike

Rewriting Interfaces • Developed An Interface Public interface Do. It { void do. Something(int Rewriting Interfaces • Developed An Interface Public interface Do. It { void do. Something(int i); } • Want to Add A Method Public interface Do. It { void do. Something(int i); int do. Something. Else(String s); } • Add A Method Public interface Do. It. Plus extends Do. It { boolean do. Something. Else(String s); }

Interfaces & Multiple Inheritance • The Java programming language does not permit multiple inheritance, 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 Grouped. Interface extends Interface 1, Interface 2, Interface 3 { Multiple Interface public interface Grouped. Interface extends Interface 1, Interface 2, Interface 3 { // constant declarations // base of natural logarithms double E = 2. 718282; // method signatures void do. Something (int i, double x); int do. Something. Else(String s); }

Summary of Interfaces • A protocol of communication between two objects • Contains signatures 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 Something. Wrong { Question 1 • What’s wrong with the following interface? Public interface Something. Wrong { void a. Method(int a. Value) { System. out. println(“Hi Mom” } }

Answer 1 • It has a method implementation in it. It should just have Answer 1 • It has a method implementation in it. It should just have a declaration. public interface Something. Wrong { void a. Method(int a. Value); }

Question 2 • Is the following interface valid? Public interface Marker { } Question 2 • Is the following interface valid? Public interface Marker { }

Answer 2 • Yes. Methods are not required. Answer 2 • Yes. Methods are not required.

Abstract Classes Abstract Classes

Abstract Classes and Methods • An abstract class is a class that is declared 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 move. To(double x, double y);

Abstract Classes and Methods • If a class includes abstract methods, the class itself Abstract Classes and Methods • If a class includes abstract methods, the class itself must be declared abstract. public abstract class Graphic. Object { 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. Abstract. Class. static. Method();

Interfaces vs Abstract Classes • An interface is a reference type, similar to a 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 Graphic. Object { int MIN_SIZE = 10; void Interfaces vs Abstract Classes public interface Graphic. Object { int MIN_SIZE = 10; void move. To(int new. X, int new. Y); void draw(); } class Circle implements Graphic. Object { void move. To(int new. X, int new. Y) {. . . } void draw() {. . . } }

Interfaces vs Abstract Classes abstract class Graphic. Object { int MIN_SIZE = 10; int Interfaces vs Abstract Classes abstract class Graphic. Object { int MIN_SIZE = 10; int x, y; void move. To(int new. X, int new. Y) {. . . } abstract void draw(); } class Circle extends Graphic. Object { void draw() {. . . } }

Abstract Class Implements Interface • A class that implements an interface must implement all 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 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 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 methods that are declared but not implemented. Subclasses then provide the implementations for the abstract methods.

Question public class Class. A { public void method. One(int i) {} public void Question public class Class. A { public void method. One(int i) {} public void method. Two(int i) {} public static void method. Three(int i) {} public static void method. Four(int i) {} } public class Class. B extends Class. A { public static void method. One(int i) {} public void method. Two(int i) {} public void method. Three(int i) {} public static void method. Four(int i) {} } • What method overrides a method in the superclass?

Answer Question 1 a: Which method overrides a method in the superclass? Answer 1 Answer Question 1 a: Which method overrides a method in the superclass? Answer 1 a: method. Two Question 1 b: Which method hides a method in the superclass? Answer 1 b: method. Four Question 1 c: What do the other methods do? Answer 1 c: They cause compile-time errors.

Numbers & Strings Numbers & Strings

Numbers Classes • When working with numbers, most of the time you use the 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 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 Number Wrapper Classes Number Double Byte Integer Float Short Long

Why Use Number Object? • As an argument of a method that expects an 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 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 String 1. concat(string 2); • Concatenating Strings • String class includes a concat() method String 1. concat(string 2); • 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, Creating Format Strings • Use printf() and format() to print output System. out. printf(“%f, %d”, float. V, int. V); • String class includes a format() method String fs; fs = String. format(“%f, %d”, float. V, int. V); System. out. println(fs);

Converting Strings to Numbers • Use value. Of() of Number subclasses o Byte, Integer, Converting Strings to Numbers • Use value. Of() of Number subclasses o Byte, Integer, Double, Float, Long, and Short String abc = “ 12. 3”; float a = (Float. value. Of(abc)). float. Value();

Converting Numbers to Strings • Concatenate “i” with an empty string int i = Converting Numbers to Strings • Concatenate “i” with an empty string int i = 5; String s 1 = “” + i; • Use to. String() of Number subclasses int i; String s 2 = Integer. to. String();

More Methods in String • More methods in String class • char. At(…) • More Methods in String • More methods in String class • char. At(…) • substring(…) • split(…) • trim() • to. Lower. Case(), to. Upper. Case() • index. Of(…) • contains(…) • …

String. Builder Class • String. Builder objects are like String objects, except that they String. Builder Class • String. Builder objects are like String objects, except that they can be modified. • length() • capacity() // number of char spaces allocated • append() • insert() • delete() • replace() • reverse() • to. String()

Questions • What is the initial capacity of the following string builder? (Hints: string Questions • What is the initial capacity of the following string builder? (Hints: string length = 26) String. Builder sb = new String. Builder("Able was I ere I saw Elba. ");

Answers • Initial string length + 16 = 26 + 16 = 42. Answers • Initial string length + 16 = 26 + 16 = 42.

Generics Generics

Why Use Generics? • Generics enable types (classes and interfaces) to be parameters when 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 reuse the same code with different inputs.

Why Use Generics? (continued) • Strong type checks at compile time. A Java compiler 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 = Why Use Generics? (continued) • Elimination of casts. // Without generics List list = new Array. List(); list. add(“hello”); String s = (String) list. get(0); // With generics List list = new Array. List(); list. add(“hello”); String s = list. get(0);

Generics • Non-Generic version of Box class: public class Box { private Object obj; 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 Box. Demo 1 { Generics (continued) • Non-Generic version of Box class: public class Box. Demo 1 { public static void main(String[] args) { // ONLY place Integer objects into this box! Box int. Box = new Box(); int. Box. add(new Integer(10)); Integer some. Int = (Integer)int. Box. get(); System. out. println(some. Int); } }

Generics (continued) • Without Generics – runtime Class. Cast. Exception public class Box. Demo Generics (continued) • Without Generics – runtime Class. Cast. Exception public class Box. Demo 2 { public static void main(String[] args) { // ONLY place Integer objects into this box! Box int. Box = new Box(); int. Box. add(“ 10”); Integer some. Int = (Integer)int. Box. get(); System. out. println(some. Int); } }

Generic Class • A generic class is defined with the following format: class Class. Generic Class • A generic class is defined with the following format: class Class. Name { } • class name • type parameters (also called type variables) T 1, … • 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 Generic Types • Generic version of Box class. public class Box { 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 Generic Types • Multiple type parameters (each parameter must be unique within its declaring class or interface) Box • Generic type innovation replaces T with some concrete type Box int. Box = new Box(); int. Box. add(new Integer(10)); Integer some. Int = int. Box. get(); int. Box. set(“ 10”); // compilation error

Type Parameter Naming Conventions • By convention, type parameter names are single, uppercase letters. 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. – 2 nd, 3 rd, 4 th types

Type Inference • Determines the type argument(s) that make the invocation applicable using the 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 pick(T t 1, T t 2) { return t 2; } Serializable s = pick(“a”, new Array. List());

Type Inference • Define a static generic method public static <U> void add. Box(U Type Inference • Define a static generic method public static void add. Box(U u, List> boxes) { Box box = new Box(); box. add(u); boxes. set(box); } • Use the method (with type inference) Box. Demo. set. Box(Integer. value. Of(10), list. Of. Int. Boxes); // type inference: let compiler infer the type Box. Demo. add. Box(Integer. value. Of(20), list. Of. Int. Boxes);

Bounded Type Parameters • Bounded type parameter restricts the kind of types that are 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 void inspect(U u) { System. out. println(“T: “ + t. get. Class(). get. Name()); System. out. println(“U: “ + u. get. Class(). get. Name()); }

The Need for Wildcards • Circle is a kind of (or subtype) Shape. • The Need for Wildcards • Circle is a kind of (or subtype) Shape. • String is a kind of Object. • List is a kind of Collection. • BUT, List is NOT a kind of List. § 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 “? Wildcards • In generics, an unknown type is represented by the wildcard character “? ”. • Upper bounded wildcard Class. Name • Lower bounded wildcard Class. Name • Unbounded wildcard Class. Name

Upper Bounded Wildcards • Upper bounded wildcard (“an unknown type that is a subtype Upper Bounded Wildcards • Upper bounded wildcard (“an unknown type that is a subtype of call”) § e. g. Number: Integer, Double, Float, Number Class. Name List

Unbounded Wildcards • Unbounded wildcard: list of unknow type <? > OR <? extends Unbounded Wildcards • Unbounded wildcard: list of unknow type OR // List, List, List, List public static void print. List(List list) { for (Object e : list) System. out. println(e + “ “); System. out. println(); // public static void print. List(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 Lower Bounded Wildcards • Lower bounded wildcard (“an unknown type that is a super type of call”) • e. g. Integer: Integer, Number, Object Class. Name List public static void add. Numbers(List list) { for (int i = 1; i <= 10; i++) { list. add(i); } }

Type Erasure • Type erasure: a process where the compiler removes all information related 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 is translated to type Box, which is called the raw type.

Question 1 • What can you do with it? public class Animal. House<E> { Question 1 • What can you do with it? public class Animal. House { private E animal; public void send. Animal(E x) { animal = x; } public E get. Animal() { return animal; } } public class Animal {} public class Cat extends Animal {} public class Dog extends Animal {} Animal. House house = new Animal. House();

Answer 1 • Failed to compile. Animal. House<Cat> and Animal. House<Animal> are not compatible Answer 1 • Failed to compile. Animal. House and Animal. House are not compatible types, even though Cat is a subtype of Animal.

Question 2 • What can you do with it? public class Animal. House<E> { Question 2 • What can you do with it? public class Animal. House { private E animal; public void send. Animal(E x) { animal = x; } public E get. Animal() { return animal; } } public class Animal {} public class Cat extends Animal {} public class Dog extends Animal {} Animal. House house = new Animal. House();

Answer 2 • Failed to compile. Animal. House<Cat> and Animal. House<Animal> are not compatible Answer 2 • Failed to compile. Animal. House and Animal. House are not compatible types, even though Cat is a subtype of Animal.

Question 3 • What can you do with it? public class Animal. House<E> { Question 3 • What can you do with it? public class Animal. House { private E animal; public void send. Animal(E x) { animal = x; } public E get. Animal() { return animal; } } public class Animal {} public class Cat extends Animal {} public class Dog extends Animal {} Animal. House house = new Animal. House(); house. set. Animal(new Cat());

Answer 3 • Failed to compile. Ø The first line is acceptable. It’s OK 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 set. Animal method cannot be used.

Question 4 • What can you do with it? public class Animal. House<E> { Question 4 • What can you do with it? public class Animal. House { private E animal; public void send. Animal(E x) { animal = x; } public E get. Animal() { return animal; } } public class Animal {} public class Cat extends Animal {} public class Dog extends Animal {} Animal. House house = new Animal. House (); house. set. Animal(new Dog());

Answer 4 • Compiles with a warning. • The compiler doesn’t know what type 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

Packages • A package is a grouping of related types providing access protection and 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 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 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, 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 Referring By Its Qualified Name • Use the member’s fully qualified name from a different package graphics; public class Rectangle() {} package othersome. Package; graphics. Rectangle my. Rect = new graphics. Rectangle();

Importing a Package Member • To import a specific member into the current file, 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 other. Package; import graphics. Rectangle; Rectangle my. Rect = new Rectangle();

Importing an Entire Package • To import all the types contained in a particular Importing an Entire Package • To import all the types contained in a particular package, use the import statement with the asterist (*) wildcard character. package other. Package; import graphics. *; Rectangle my. Rect = new Rectangle(); Circle my. Circle = new Circle();

Packages Imported Automatically • For convenience, the Java compiler automatically imports three entire packages 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 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 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 my. Rect;

Static Import Statement • The static import statement gives you a way to import 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, 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: srccomacmegraphicsRectangle. java

Managing Source and Class Files • The compiled. class file should be arranged in Managing Source and Class Files • The compiled. class file should be arranged in different directory. c: classescomacmegraphicsRectangle. 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: Usersjamesclasses

Questions 1 • Assume that you have written some classes. Belatedly, you decide that 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: 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 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 • 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 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 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 http: //en. wikipedia. org/wiki/Naming_convention_(programming)#Java

Naming Conventions - Classes • Class names should be nouns in Upper Camel. Case, Naming Conventions - Classes • Class names should be nouns in Upper Camel. Case, 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 Camel. Case; that Naming Conventions - Methods • Methods should be verbs in lower Camel. Case; that is, with the first letter lowercase and the first letters of subsequent words in uppercase. public in get. Gear() { }

Naming Conventions - Variables • Local variables, instance variables, and class variables are also Naming Conventions - Variables • Local variables, instance variables, and class variables are also written in lower Camel. Case. • 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 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. 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?

What’s Next? • Classes from Technology Service Group (TSG)@ROLF http: //www. techsamaritan. org/ § 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++, Java. Script, 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! 謝 謝! Thank you! 謝 謝!

Think Java: Java Programming Language Part 2 Chia James Chang cjameschang@yahoo. com Think Java: Java Programming Language Part 2 Chia James Chang [email protected] com