1 introduction to java professor yihjia tsai tamkang university
Post on 21-Dec-2015
245 views
TRANSCRIPT
1
Introduction To Java
Professor Yihjia TsaiTamkang University
2
Basic OOP Notions Java
Instance variables - describe the data in abstract data types (each object instance has its own copy of the data)
Class variables - describe the data in abstract data types all object instances share the value of the data (called static fields in Java)
Messages request for an operation Methods implementation of a request
3
Data and Methods/Interface
DATA
Oper1
Oper3
Ope
r 4O
per2
Public
Private
4
Introduction to Java Basic Ideas
All Java Programs , unlike C++ are built from classes, in this way Java is more strictly an OOP
A class is said to contain fields (members in C++) and methods (member functions in C++)
5
Fundamental Ideas
Java was designed with security and portability in mind
Supports standard length built in types Java source gets translated into something called
Java byte code that is run on something called the Java virtual machine.
Java bytecode is the machine language of the Java virtual machine
The virtual machine assigns each application its own runtime, which isolates applications from each other.
6
Java Infrastructure
javacjavac.java
javajavabytecode
.class file produced
This is the JVM
7
A Code Example
class HelloWorld {
public static void main(String[] args) {System.out.println(“Hello mom”);
}
}
Type this in , compile it, and add Javato your resume ;)
8
Similarities and differences from C++?
The Built In Types Comments Named Constants Flow of Control
9
The Built In Types
boolean true or false
char 16 bit Unicode 1.1 character
byte 8 bits
short 16 bit integer signed
int 32 bit signed integer
long 64 bit signed integer
float , double IEEE 754
10
Comments
Are identical to C++ except for javadoc // Comment till end of line /* Comments spanning a line */ /** */ javadoc comment
javadoc produces html documentation on methods , constructors and so on
11
Named Constants
class CircleStuff {static final double = 3.1416;
}
class Suit { public final static int CLUBS = 1;
public final static int DIAMONDS = 2; public final static int HEARTS = 3; public final static int SPADES = 4;
}
12
Classes and Objects
Java classes have fields and methods
Fields and Methods in Java can have associated visibility Public Private Package Protected
13
Methods
class Point { // ..public void clear() {
x = 0;y = 0;
} public double distance(Point other) {
double xdiff , ydiff;xdiff = x - other.x;ydiff = y - other.y;return Math.sqrt(xdiff * xdiff + ydiff * ydiff);
} }
14
Packages
Used to avoid name conflicts Java has adopted a more formal notion of a
package that has a set of types and subpackages as members.
Packages are named and can be imported - we'll look at a few examples.
Package names form a hierarchy with parts separated by dots.
When you use part of a package , either you use its fully qualified name or you import all or part of the package.
15
Examples
class Date1 {public static void main(String[] args) {
java.util.Date now = new java.util.Date();System.out.println(now);
}} import java.util.Date; class Date2 {
public static void main(String[] args) {Date now = new Date();System.out.println(now);
}}
16
Self Reference
Java unlike C++ has no notion of a pointer There is still a this construct however - an
example will suffice class Point {
// ...
public void clear () {
this.x = 0;
this.y = 0;
}
// ...
}
17
Creating Objects
Use new Invokes constructor No destructor Super and this
18
Arrays
class Deck {final int DECK_SIZE = 52;Card[ ] = new Card[DECK_SIZE]; // .... Init the array somewherepublic void print() {
for (int i = 0; i < cards.length; i++)System.out.println(cards[i]);
} // ...
}
19
Strings are Built In Java
class Yadayadayada {public static void main (String[ ] args ) {
/// yadayadayada}//
}
There is also a StringBuffer class
20
Tokenizing Strings
import java.util.*;
String stg = “when the going gets weird the weird turn pro”;
StringTokenizer tokens = new StringTokenizer (stg);
while (tokens.hasMoreElements() ) {String next = tokens.nextToken();System.out.println(next);
}
21
Inheritance
One of major aspects of OOP is inheritance - lets look at an example in Java
You can inherit , override , or reuse behavior of parent class
Note that Pixel objects can be used by any code designed to work with Point objects.
If a method expects a parameter of type Point, you can hand it a Pixel object instance and it still works just fine.
22
InheritanceInheritance
class Pixel extends Point {
Color color;
public void clear() {
super.clear();
color = null;
}
}
Only public inheritance !
23
Java Doesn't support MI of Implementation
interface Lookup {
// Return the value associated w/ name or null
Object find (String name);
}
class Foo implements Lookup extends Bar {
// Foo must provide all the Lookup methods
}
24
Using an Interface
Now lets look at some code that that uses the Lookup interface
void processValues (String[] names, Lookup table) {
for (int i = 0; i<names.length; i++) {Object value = table.find(names[i]);if (value != null)
processValue(names[i], value);}
}
25
A Class that Implements
the Lookup Interface Now lets look at a class that implements the
interface
class SimpleLookup implements Lookup {
private String[] Names;
private Object[] Values;
public Object find(String name) {
for (int i = 0; i<Names.length; i++) {if (Names[i].equals(name)) return Values[i];
}
} // ....
}
26
Exceptions
Java uses checked exceptions to manage error handling. Exceptions force a programmer top deal with errors. If a checked exception is not handled, this noticed when the error happens, not latter when problems have potentially compounded.
A method that detects an unusual error condition throws an exception. Exceptions in turn may be caught by code further back on the calling stack - this prior code can handle the exception and continue processing.
Un-handled exceptions are handled by a default handler in the Java implementation which may report the exception and terminate the thread of execution.
27
More General Ideas About Exceptions in Java
Exceptions in Java are objects , with type , methods and fields of data. This representation is handy because an exception can include data or methods to report or recover from certain conditions.
Exceptions are generally extensions of the Exception class which provides a string field to describe the error.
28
class IllegalAverageException extends Exception {};
class MyUtilities {
public double averageOf ( double[] vals , int i , int j)throws IllegalAverageException {
try {
return (vals[i] + vals[j]) / 2;
}
catch (IndexOutOfBoundsException e) {throw new IllegalAverageException(); }
}
}
An Example of Exceptions
29
Text Input
System.in is a java.io.InputStream reads raw bytes
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
InputStreamReader coverts from bytes to Unicode
BufferedReader supports String readLine()returns null at EOF
30
File Text I/O
PrintWriter out = new PrintWriter(new FileWriter(fileName));
BufferedReader in = new BufferedReader(new FileReader(fileName));
31
References
Flanagan, D., Java in a Nutshell, 2nd ed., O’Reilly, 1997. ISBN 156592262X.
Harold, E.R., Java Network Programming, 3rd ed., O’Reilly, 2004. ISBN 1565922271.
Niemeyer, P., J. Knudsen, Learning Java, 3rd ed. , O’Reilly, 2005. ISBN 0596008732.
Meyer, J., T. Downing, Java Virtual Machine, O’Reilly, 1997. ISBN 1565921941.