310 likes | 441 Views
Introduction To Java. Professor Yihjia Tsai Tamkang University. Basic OOP Notions Java. Instance variables - describe the data in abstract data types (each object instance has its own copy of the data)
E N D
Introduction To Java Professor Yihjia Tsai Tamkang University
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
Data and Methods/Interface Public Oper1 Oper2 DATA Oper4 Private Oper3
Introduction to JavaBasic 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++)
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.
Java Infrastructure .class file produced .java bytecode java javac This is the JVM
A Code Example Type this in , compile it, and add Java to your resume ;) class HelloWorld { public static void main(String[] args) { System.out.println(“Hello mom”); } }
Similarities and differences from C++? • The Built In Types • Comments • Named Constants • Flow of Control
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
Named Constants class CircleStuff { static final double p = 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; }
Classes and Objects • Java classes have fields and methods • Fields and Methods in Java can have associated visibility • Public • Private • Package • Protected
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); } }
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.
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); } }
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; } // ... }
Creating Objects • Use new • Invokes constructor • No destructor • Super and this
Arrays class Deck { final int DECK_SIZE = 52; Card[ ] = new Card[DECK_SIZE]; // .... Init the array somewhere public void print() { for (int i = 0; i < cards.length; i++) System.out.println(cards[i]); } // ... }
Strings are Built In Java class Yadayadayada { public static void main (String[ ] args ) { /// yada yadayada } // } There is also a StringBuffer class
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); }
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.
Inheritance class Pixel extends Point { Color color; public void clear() { super.clear(); color = null; } } Only public inheritance !
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 }
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); } }
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]; } } // .... }
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.
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.
An Example of Exceptions 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(); } } }
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
File Text I/O PrintWriter out = new PrintWriter(new FileWriter(fileName)); BufferedReader in = new BufferedReader( new FileReader(fileName));
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.