Presentation is loading. Please wait.

Presentation is loading. Please wait.

Think Java: Java Programming Language Part 2 Chia James Chang (Materials are based on: The Java Tutorials)

Similar presentations


Presentation on theme: "Think Java: Java Programming Language Part 2 Chia James Chang (Materials are based on: The Java Tutorials)"— Presentation transcript:

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

2 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?

3 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-jsp- 136079.html

4 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

5 Quick Review (Language Basics, Classes, Objects)

6 Language Basics Java Reserved Words Variables Operators Expressions Statements Blocks Control Flow Statements

7 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

8 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)

9 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)

10 Primitive Data Types data typesizedefault byte8-bit signed0 short16-bit signed0 int32-bit signed0 long64-bit signed0L float32-bit signed (single-precision)0.0f double64-bit IEEE 754 (double-precision)0.0d booleantrue and falsefalse char16-bit Unicode char‘\u0000’

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

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

13 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;

14 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) {... }

15 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.”); }

16 Control Flow Statements if switch while do for break continue return try/throw

17 Object-Oriented Programming (OOP)

18 Classes Objects Inheritance Interfaces Abstract Classes Packages

19 Object-Oriented Programming (OOP) A fundamental principle of object-oriented programming:  Encapsulation  Inheritance  Polymorphism

20 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 }

21 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);

22 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.

23 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.

24 Nested Classes

25 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.

26 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 { … }

27 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.

28 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.

29 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.

30 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.

31 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; }

32 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; }

33 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?

34 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.

35 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 }

36 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 }

37 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

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

39 Interfaces

40 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.

41 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.

42 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.

43 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.

44 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 comma-separated list of parent interfaces (if any), and the interface body.

45 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); }

46 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 BikeTandem Bike

47 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); }

48 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.

49 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); }

50 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

51 Question 1 What’s wrong with the following interface? Public interface SomethingWrong { void aMethod(int aValue) { System.out.println(“Hi Mom” }

52 Answer 1 It has a method implementation in it. It should just have a declaration. public interface SomethingWrong { void aMethod(int aValue); }

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

54 Answer 2 Yes. Methods are not required.

55 Abstract Classes

56 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);

57 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();

58 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.

59 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() {...} }

60 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() {...} }

61 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 }

62 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.

63 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- methods that are declared but not implemented. Subclasses then provide the implementations for the abstract methods.

64 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?

65 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.

66 Numbers & Strings

67 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.

68 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

69 Number Wrapper Classes Number Byte Double Float IntegerShort Long

70 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).

71 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.

72 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” + “!”;

73 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);

74 Converting Strings to Numbers Use valueOf() of Number subclasses o Byte, Integer, Double, Float, Long, and Short String abc = “12.3”; float a = (Float.valueOf(abc)).floatValue();

75 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();

76 More Methods in String More methods in String class charAt(…) substring(…) split(…) trim() toLowerCase(), toUpperCase() indexOf(…) contains(…) …

77 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()

78 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.");

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

80 Generics

81 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.

82 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.)

83 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 list = new ArrayList (); list.add(“hello”); String s = list.get(0);

84 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; } }

85 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); } }

86 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); } }

87 Generic Class A generic class is defined with the following format: class ClassName { } 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

88 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; } }

89 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 intBox = new Box (); intBox.add(new Integer(10)); Integer someInt = intBox.get(); intBox.set(“10”); // compilation error

90 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, 3rd, 4 th types

91 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 t1, T t2) { return t2; } Serializable s = pick(“a”, new ArrayList ());

92 Type Inference Define a static generic method public static void addBox(U u,List > boxes) { Box box = new Box (); box.add(u); boxes.set(box); } Use the method (with type inference) BoxDemo. setBox(Integer.valueOf(10), listOfIntBoxes); // type inference: let compiler infer the type BoxDemo.addBox(Integer.valueOf(20),listOfIntBoxes);

93 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.getClass().getName()); System.out.println(“U: “ + u.getClass().getName()); }

94 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.

95 Wildcards In generics, an unknown type is represented by the wildcard character “?”. Upper bounded wildcard ClassName Lower bounded wildcard ClassName Unbounded wildcard ClassName

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

97 Unbounded Wildcards Unbounded wildcard: list of unknow type OR // List,List,List,List public static void printList(List 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();

98 Lower Bounded Wildcards Lower bounded wildcard (“an unknown type that is a super type of call”) e.g. Integer: Integer, Number, Object ClassName List public static void addNumbers(List list) { for (int i = 1; i <= 10; i++) { list.add(i); } }

99 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.

100 Question 1 What can you do with it? public class AnimalHouse { 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 ();

101 Answer 1 Failed to compile. AnimalHouse and AnimalHouse are not compatible types, even though Cat is a subtype of Animal.

102 Question 2 What can you do with it? public class AnimalHouse { 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 ();

103 Answer 2 Failed to compile. AnimalHouse and AnimalHouse are not compatible types, even though Cat is a subtype of Animal.

104 Question 3 What can you do with it? public class AnimalHouse { 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 Cat());

105 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.

106 Question 4 What can you do with it? public class AnimalHouse { 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());

107 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.

108 Packages

109 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.

110 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 { }

111 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

112 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

113 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();

114 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();

115 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();

116 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)

117 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.*;

118 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;

119 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);

120 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

121 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

122 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 NameClass Name mygame.serverServer mygame.sharedUtilities mygame.clientClient

123 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;

124 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 NameClass Name mygame.serverServer mygame.sharedUtilities mygame.clientClient

125 Answer 2 Within the mygame directory: In mygame/client/ place: Client.java In mygame/server/ place: Server.java In mygame/shared/ place: Utilities.java

126 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 NameClass Name mygame.serverServer mygame.sharedUtilities mygame.clientClient

127 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;

128 Naming Conventions http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java

129 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 { }

130 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() { }

131 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;

132 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;

133 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;

134 What’s Next?

135 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/

136 Thank you! 謝 謝 !

137 Think Java: Java Programming Language Part 2 Chia James Chang cjameschang@yahoo.com


Download ppt "Think Java: Java Programming Language Part 2 Chia James Chang (Materials are based on: The Java Tutorials)"

Similar presentations


Ads by Google