Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. Prof. Hyoung-Joo Kim Contents(1) 1.1 Getting Started 1.2 Variables 1.3 Comments in Code 1.4 Named Constants 1.5 Flow of Control 1.6 Classes and Objects 1.7 Methods and Parameters 1.8 Arrays Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 2 Contents(2) 1.9 String Objects 1.10 Extending a Class 1.11 Interfaces 1.12 Exceptions 1.13 Packages 1.14 The Java Infrastructure 1.15 Other Topics Briefly Noted Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 3 1.1 Getting Started Class and Object Class a factory with blueprints and instructions to build gadgets two members field : data and making up the state of the object or class method : collection of statements that operate on the fields Objects gadgets the factory makes instances of the class Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 4 “Hello, World”(1) class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, world”); } } String objects the main method’s only parameter System.out.println println method on the System class’s out object main one of a few special method in Java when run, main can create objects, evaluate expressions, invoke other methods, etc. Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 5 “Hello, World”(2) Compilation $ javac HelloWorld.java $ ls HelloWorld.class HelloWorld.class Java compiler(javac) compiles the source into Java bytecodes Execution $ java HelloWorld Hello, World Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 6 1.2 Variables Every variable must have a type Java has no “default” types Primitive data types boolean char byte short int long float double either true or false 16-bit Unicode 1.1 character 8-bit integer ( signed ) 16-bit integer ( signed ) 32-bit integer ( signed ) 64-bit integer ( signed ) 32-bit floating point ( IEEE 754-1985 ) 64-bit floating point ( IEEE 754-1985 ) Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 7 “Fibonacci” Program(1) Class Fibonacci { /** Print out the Fibonacci sequence for values < 50 */ public static void main(String[] args) { int lo = 1; int hi = 1; System.out.println(lo); while(hi < 50) { System.out.println(hi); hi = lo + hi; // new hi lo = hi - lo; // new lo is (sum - old lo) I.e., the old hi } } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 8 “Fibonacci” Program(2) Compilation & Execution $ javac Fibonacci.java $ ls Fibonacci.class Fibonacci.class $ java Fibonacci 1 1 2 3 5... Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 9 1.3 Comments in Code Three // comment characters from // to the end of the line are ignored /* comment */ styles of comments character between /* and the next */ are ignored, including line terminators \r, \n, or \r\n /** comment */ documentation comment ( for short, doc comment ) characters between /** and the next */ are ignored, including line terminators a tool called javadoc extracts documentation comments and generates HTML documentation Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 10 1.4 Named Constants Why do programmer prefer named constants? a form of documentation easy to maintain program Named constants are created by declaring a variable as static and final providing its initial value class CircleStuff { static final double = 3.1416; } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 11 1.4.1 Unicode Characters You write Java code in Unicode - an international character set standard Unicode characters are 16 bits and provide a character range large enough to write the major language Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 12 1.5 Flow of Control(1) Decide which statements are executed Similar to C-derived programming language (e.g., C, C++…) Think of output of running next prograrm! Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 13 1.5 Flow of Control(2) class ImprovedFibonacci { /** Print out the first few Fibonacci numbers, marking events with a ‘*’ */ static final int MAX_INDEX = 10; public static void main(String[] args) { int lo =1, hi =1; String mark; System.out.println(“1: “ + lo); for(int i=2; i < MAX_IINDEX; i++) { if(hi%2 == 0) mark = “ *”; else mark =“”; System.out.println(I + “: “ + hi + mark); hi = lo + hi; // new hi lo = hi - lo; /* new lo is (sum - old lo) I.e., the old hi */ } } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 14 1.6 Classes and Objects Relationship between classes and objects an object have a type that type is the object’s class Each class has two kinds of members fields - data variables associated with a class and its objects methods - contain executable code of a class Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 15 1.6.1 Creating Objects(1) Creating objects (= instantiations) objects are created using new keyword newly created objects are allocated within heap objects are accessed via object references instantiation, instance, instance variable creating an object from a class definition is instantiation created objects are called instances the fields in objects are instance variables Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 16 1.6.1 Creating Objects(2) class Point { public double x, y; public static void main(String[] args) { Point lowerLeft = new Point(); // creating objects Point upperRight = new Point(); lowerLeft.x = 0.0; upperRight.x = 10.0; lowerLeft.y = 0.0; upperRight.y = 10.0; } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 17 1.6.2 Static or Class Fields(1) Static(class) fields known as class variables shared among all objects of a class declared by static keyword Non-static (per-object) fields each object has distinct fields from other object Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 18 1.6.2 Static or Class Fields(2) class Point { public double x, y; public static Point origin = new Point(); public static void main(String[] args) { System.out.println("Origin.x = " + Point.origin.x); System.out.println("Origin.y = " + Point.origin.y); } } Origin.x = 0.0 Origin.y = 0.0 Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 19 1.6.3 The Garbage Collector Unreferenced Java objects are automatically reclaimed by a garbage collector The garbage collector runs in the background and tracks object references Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 20 1.7 Methods and Parameters Methods and parameters methods - operations of a class parameters - arguments of methods Implementation benefits hiding of object orientation Data encapsulation hiding data behind methods so that it is inaccessible to other objects Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 21 1.7.1 Invoking a Method(1) To invoke a method, provide an object reference and the method name, separated by a dot(.) To return more than one value, create an object to hold return values and return that object receiving object ( for short, receiver) the object on which the method is invoked Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 22 1.7.1 Invoking a Method(2) class Point { public double x, y; public double distance(Point that){ double xdiff, ydiff; xdiff = x - that.x; ydiff = y - that.y; return Math.sqrt(xdiff *xdiff + ydiff*ydiff); } public static void main(String[] args) { Point lowerLeft = new Point(); Point upperRight = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 10.0; upperRight.y = 10.0; distance = 14.142…. double d = lowerLeft.distance(upperRight); System.out.println("distance = " + d); } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 23 1.7.2 The this Reference Implicit reference named “this” a reference to the current(receiving) object class Point { public double x, y; public void move(double x, double y) { this.x = x; this.y = y; } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 24 1.7.3 Static or Class Methods Static(class) methods declared using static keyword shared among on static fields of all instance object can’t directly access non-static members Non-static(per-object) methods each object has distinct method from other instance class AnIntegerNamedX { static private int x; static public int getX() { return x; } static public void setX(int newX) { x = newX; } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 25 1.8 Arrays(1) Array a collection of variables all of the same type Array size is fixed and provided from the length field of array object an IndexOutOfBoundsException is thrown in case of using an index outside the bounds of the array Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 26 1.8 Arrays(2) class Deck { final int DECK_SIZE = 52; card[] cards = new Card[DECK_SIZE]; public void print() { for (int i=0; i< cards.length; i++) System.out.println( cards[i] ); } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 27 1.9 String Objects(1) String class provide language-level support for initialization provide a variety of methods String objects are immutable str = “redwood”; // ….. Do do something with str…. str = “oak”; /* give a new value to object reference str, not to the contents of the string */ StringBuffer class provide for mutable strings Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 28 1.9 String Objects(2) class BetterStringsDemo { public static void main(String[] args) { String myName = "Petronius"; String occupation = "Reorganization Specialist"; myName = myName + " Arbeiter"; myName += " "; myName += "(" + occupation + ")"; System.out.println("Name = " + myName); } } Name = Petronius Arbeiter (Reorganization Specialist) Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 29 1.9 String Objects(3) equals method compare two String objects to see if they have the same contents if (oneStr.equals(twoStr)) foundDuplicate(oneStr, twoStr); Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 30 1.10 Extending a Class(1) Subclass inherit all the fields and methods of superclass if providing new implementation of inherited methods, then overrides the behavior of superclass class Point { public double x, y; public void clear(){ x = 0.0; y = 0.0; } } Chap1. A Quick Tour of Java class Pixel extends Point { Color color ; public void clear() { super.clear(); color = null; } } SNU-OOPSLA-Lab. 31 1.10 Extending a Class(2) Point Class clear() x() double x double y Pixel Class y() set() clear() x() Pixel extends Point double x double y y() Color color set() Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 32 1.10.1 The Object Class Classes that do not explicitly extend any other class implicitly extend the Object class All object references are polymorphically of Object class, so Object class is the generic class for references that can refer to objects of any class The Object class defines several methods Object oref = new Pixel(); oref = “Some String” Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 33 1.10.2 Invoking Methods from Superclass super vs this super - reference things from superclass this - reference things from the current object To invoke a method uses the actual type of the object, not the type of the object reference Point point = new Pixel(); point.clear(); // uses Pixel’s clear(), not Point’s clear() Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 34 1.11 Interfaces(1) Interfaces similar to a class, but with only declarations of its methods implementation details of the methods are irrelevant the class that implements the interface is responsible for the specific implementation Class’s supertypes are superclass that it extends interfaces that it implements all the supertypes of those classes and interfaces Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 35 1.11 Interfaces(2) interface Lookup { /** Return the value associated with the name, * or null if there is no such value */ Object find(String nam); } Void processValues(String[] names, Lookup table) { for(int i=0; i<names.length; i++) { Object value = table.find(names[i]); if(value != null) processVaule(names[i], value); } } Code that uses references to Lookup objects and get the expected results, no matter the actual type of the object Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 36 1.11 Interfaces(3) 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]; } return null; // not found } // …. } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 37 1.12 Exceptions(1) Java uses checked exceptions to manage error handling Checked exceptions force you to consider what to do with errors where they may occur in the code exception is an object, with type, methods,and data Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 38 1.12 Exceptions(2) Exception object generally derived from the Exception class, which provides a string field to describe the error all exceptions is extensions of Throwable class, which is the superclass of Exception Exception Handling try-catch-finally sequence finally - clean up from either the normal code path or the exception code path Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 39 1.12 Exceptions(3) class IllegalAverageException extends Exception { } class MyUtilities { public double averageOf ( double[] vals, int i, int j ) throws IllegalAverageException { try{ return ( vals[i] + val[j] ) / 2; } catch ( IndexOutOfBoundsException e ){ throw new illegalAverageException(); } } } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 40 1.13 Packages(1) Solution for name-conflicts use a “package prefix” at the front of every class it isn’t a complete solution Packages have a set of types and subpackages as members package names are hierarchical and separated by dots in case of using a package use its fully qualified name import all or part of the package Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 41 1.13 Packages(2) When using part of a package use fully qualified name import all or part of the package Chap1. A Quick Tour of Java 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[] rgs){ Date now = new Date(); System.out.println(now); } SNU-OOPSLA-Lab. 42 1.13 Packages(3) Convention of naming packages complete solution for name collision use reversed Internet domain name of the organization to prefix the package name. e.g., COM.acme.package, KR.ac.snu.oopsla.package package com.sun.games; class Card { // ………… } Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 43 1.14 The Java Infrastructure Java is designed to maximize portability Java virtual machine assign each application its own runtime runtime - isolate applications from each other and provide a security model Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 44 1.15 Other Topics Briefly Noted Applet Java program that runs on the browser of client platform Make a class that extends the Applet class Make methods named as init, start, stop, destroy There is no main method Use other classes and utilities as the Java application program Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 45 1.15 Other Topics Briefly Noted Applet example public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } Chap1. A Quick Tour of Java void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { g.drawRect(0, 0, size().width - 1, size().height - 1); g.drawString(buffer.toString(), 5, 15); } } SNU-OOPSLA-Lab. 46 1.15 Other Topics Briefly Noted RMI(Remote Designing Method Invocation : At Server Part) a Remote Interface import java.rmi.*; import java.rmi.*; import java.rmi.server.*; import java.io.Serializable; public interface Task extends Remote { TaskObject getTaskObjcet() throws RemoteException; } public interface TaskObject extends Serializable { type1 task1(); type2 task2(); ……….. } Chap1. A Quick Tour of Java public class Server{ public static void main(String args[]){ if(System.getSecurityManager() == null){ System.setSecurityManager(new RMISecurityManager()); } try{ TaskImpl task = new TaskImpl(); Naming.rebind(“Task”, task); }catch(Exception e){ ………………..; } } SNU-OOPSLA-Lab. rmiregistry 사용 47 1.15 Other Topics Briefly Noted RMI(Remote Method Invocation : At Client Part) Use the same interface as the server Use following code to invoke remote object …………….. if(System.getSecurityManager() == null) System.setSecurityManager()(new RMI…()); String url = “rmi://server_address”; try{ Task t = (Task)Naming.lookup(“Task”); TaskObject to = t.getTaskObject(); }catch(Exception e){ ……….. } rmiregistry 사용 Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 48 1.15 Other Topics Briefly Noted Servlet Make Servlet script like CGI script generic code are the shape of following Object declarations (like other Java applications) out.println(“<HTML>”); out.println(“<HEAD><TITLE> …. </TITLE></HEAD>”); ………………. out.println(“</HTML>”); Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 49 1.15 Other Topics Briefly Noted Java & XML Many XML parsers are implemented by Java DOM : Use Object Model Makes a model (like tree structure) Provide traversal methods SAX : Event Driven XML Parser Makes a event handler class Makes the methods to be invoked when an event occur SAX parser invokes an appropriate method when an event occur Chap1. A Quick Tour of Java SNU-OOPSLA-Lab. 50