is object oriented

Everything belongs to a class (no global Lecture 5: Java Introduction variables, directly). Main program is a static method in the Advanced Programming class that you run with the java Techniques command. Summer 2003

Lecture slides modified from B. Char

Java is syntactically similar to C++ Locations of Java code

Built-in types: int, float, double, char. Writing the code. Suppose we have a program that consists of just one class foo Control flow: if-then-else, for, switch. and a main procedure that uses it. Write the Comments: /* .. */ main procedure as a static method in that class. but also // …. (to end of line) The source code must be in a file named Exceptions: throw …; try {} catch{}. foo.java in your current . Compilation. Create the file foo.class via the command foo.java

Running java code (default) Multi-file definitions

To execute the main procedure in If you use several classes foo1, foo2, foo3, … foo.class, give the command create several files in the same directory foo1.java, foo2.java, foo3.java. Compile each java foo one. The compiler will automatically look for other classes in the same directory. Sometimes the compiler can figure out that foo1 requires foo2, so that compiling foo1.java will automatically cause foo2.java to be compiled… but explicit compilation means you can be sure that a file has been compiled or recompiled.

1 Classes assembled at More multi-file definitions compilation, and at run time

import bar; Contrast with C or C++ which tends to means that bar.class should be collect all classes needed into a single consulted to find definitions of executable (binary) file, before classes/definitions mentioned in the execution. current file’s programming, such as the class bar.

Classpath specified on the Classpath command line command line option for javac or java specifies a list of directories Java will look in other directories, and Java archive files (. files) besides the Separated by semi-colons on Windows standard Java system directories and javac -classpath .;E:\ MyPrograms\ jena.jar;E:\ utilities foo1.java (Windows) your current working directory Separated by colons on Solaris java -classpath .:/home/vzaychik/jena.jar:/home/vzaychik/utilities foo1 (Unix)

CLASSPATH environment classpath command option vs variable Software engineering considerations: Value is used if there is no classpath explicit invocation of the classpath on the command option. command line means it’s easier for programmers setenv CLASSPATH .:/pse/:/pse1/corejini: (on to remember or readers to discover what you set Unix) the classpath to. With fewer mistakes or misunderstandings, one has easier to maintain javac example1.java code Can put compilation directions into a make file, Compilation will look in current working will work for anyone regardless of how they set directory /pse and /pse1/corejini directories their classpath variables. This also avoids the for other class definitions. problem of typing in a long classpath repeatedly set CLASSPATH .;E:\PSE\; E:\jini1_0\lib\jini- during development: just type “make asmt1” or whatever. core.jar; (on Windows)

2 Many similarities to C++ in built-in data types, syntax Array example

import java.io.*; if, for, while, switch as in C++ /* Example of use of integer arrays*/

Strings a first-class data objects. “+” public class example2{ public static void main(String argv[]) { works with Strings, also coerces int sum = 0; int durations [] = {65, 87, 72, 75}; numbers into strings. for (int counter = 0; counter < durations.length; ++counter) { Arrays are containers. Items can be sum += durations[counter]; }; accessed by subscript. There is also a // Print out overall result. System.out.print("The average of the " + durations.length); length member. System.out.println(" durations is " + sum/durations.length + "."); } }

Static methods, static data Output members

/home/vzaychik/cs390/>javac example2.java class foo { /home/vzaychik/cs390/>java example2 … The average of the 4 durations is 74. static public int rand(int r) { …}; // static method static public int i; // static data }

all objects of that type share a common i and a common version of the method. Methods can be invoked without creating an instance of the class.

Example of non-static use of classes: In example3.java In Symphony.java

import java.io.*; /* Definition of symphony class */

/* Simple test program for Java (JDK 1.2) */ public class Symphony { public int music, playing, conducting; public class example3{ // by default classes are protected public int rating() { (known to “package”) return music + playing + conducting; public static void main(String argv[]) { } Movie m = new Movie(); } m.script = 9; m.acting = 9; m.directing = 6; Symphony s = new Symphony(); s. music = 7; s.playing = 8; s.conducting = 5; // Print out overall results. System.out.println("The rating of the movie is " + m.rating()); System.out.println("The rating of the symphony is " + s.rating()); } }

3 Compiling and running on In Movie.java Unix

/* Definition of Movie class for example 3.*/ % javac Movie.java

public class Movie { public int script, acting, directing; % javac Symphony.java public int rating() { return script + acting + directing; % javac example3.java } } % java example3 The rating of the movie is 24 The rating of the symphony is 20

Protection in methods and data members Constructors, protection

/* Definition of Movie2 class: two constructors.*/

Can be public, protected, private as in public class Movie2{ private int script, acting, directing; C++. public Movie2() { script = 5; acting = 5; directing = 5; } public Movie2(int s, int a, int d) { script =s; acting = a; directing = d; } public int rating() { return script + acting + directing; } // mutator/access methods for script public void setScript(int s) { script = s; } public int getScript() {return script;}; // mutator/access methods for acting, directing here } }

Naming conventions for Naming conventions for classes, variables classes, variables, constants

These are rules borrowed from Reiss’ Names of classes: First letter capitalized, e.g. “Software Design” textbook used in class Movie { ….} cs350. Java does not insist on them Names of methods: first letter lower case; but we recommend following coherent multi-word method names capitalized second and successive words: naming rules to reduce software public int getTime(); engineering costs. public void clear(); Names of constants: all caps final int BOARD_SIZE;

4 Inheritance abstract classes

to have class B be a subclass of class A, Subclasses used in program, inherit write “public class B extends A {….” methods and fields of superclass. But you can’t create an instance of an abstract class.

Abstract class example Interfaces

public abstract class Attraction{ public int minutes; public Attraction() {minutes = 75;} Java does not have general multiple public int getMinutes() {return minutes;} public void setMinutes (int d) { minutes = d;} inheritance. It does have limited multiple } inheritance. then class definitions for Movie and Symphony: An interface B is a class that has only class public Movie extends Attraction { ….} declarations. and public class A implements B, C, D {…} public Symphony extends Attraction { …} means that A inherits the methods of B,C, can use Attraction x; x = new Movie() or x = new and D (and can have methods and members Symphony; in a program of its own).

Defining an abstract class Defining an interface class

public abstract class GeometricObject //Definition starts with “interface” instead of { “class” // class definition goes here as interface FloatingVessel { normal int navigate(Point from, Point to); … // Point is another user-defined class } void dropAnchor(); void weighAnchor(); }

5 Superclass, subclass Packages class A1 implements A {….} package onto.java.entertainment; class B1 extends B {….} public abstract class Attraction {….} class C { public int method1(A a, B b) {…} … public method2(…) { Attraction.java must be in an onto/java/entertainment int result; B1 b1Object; A1 a1Object; subdirectory. If this file is in b1Object = new B1(…); /home/vzaychik/cs390/asmt4/onto/java/entertainment a1Object = new A1(…): The value of the CLASSPATH variable should include the result = method1(a1Object, b1Object); value /home/vzaychik/cs390/asmt4. ….} }

Importing classes that belong Package invocation to packages If a class example7 is in the package onto.java.entertainment, import onto.java.chapter7.entertainment; invoke through the full package name // imports entertainment class that java onto.java.entertainment.example7 // belongs to onto.java package import java.io.ObjectInputStream; even if you’re in example7’s directory. // imports ObjectInput class from java.io // package import java.net.*; // imports any class // needed from java.net package

What does “final” mean? I/O

public final class FinalCircle extends from command line arguments GraphicCircle { … } from the terminal When a class is declared with the final from files modifier, it means that it cannot be extended. It’s a way of declaring constants for a class: final int BUFFERSIZE = 10;

6 I/O stream classes File input example

import java.io.*; Compose them together to read/write public class example5 { public static void main(String argv[]) throws IOException { to/from files: text, binary data, other FileInputStream stream = new FileInputStream("input.data"); InputStreamReader reader = new InputStreamReader(stream); kinds. StreamTokenizer tokens = new StreamTokenizer(reader); while(tokens.nextToken() != tokens.TT_EOF) {// TT_EOF built- in for tokens System.out.println("Integer: " + (int) tokens.nval); // nval built-in for tokens } stream.close(); } } Alternative: compose constructors together: StreamTokenizer tokens = new StreamTokenizer(new InputStreamReader( new FileInputStream(“input.data”)));

Execution results File output example

In input.data file in current working directory: PrintWriter writer = new PrintWriter(new 4 7 3 FileOutputStream(“output.data”)); …. writer.println(< whatever needs to be written to Output: file>); /home/vzaychik/cs390/>java example5 java example5 Integer: 4 Integer: 7 Integer: 3

File input also works with standard input redirection Composing constructors

StreamTokenizer tokens = Idea: use “System.in” stream to do reading. new StreamTokenizer( By default, this reads from the keyboard. But new InputStreamReader( if you invoke the program using “<“ for new FileInputStream(“input.data”))); standard input redirection

javac –classpath … Example1 < inputFile

then System.in will read from the inputFile instead.

7 Vector example

import java.io.*; Built-in data types import java.util.*;

public class vectorExample { public static void main(String argv[]) throws IOException{ ints, floats, chars,boolean, Strings FileInputStream stream = new FileInputStream(argv[0]); InputStreamReader reader = new InputStreamReader(stream); arrays StreamTokenizer tokens = new StreamTokenizer(reader); Vector v = new Vector();

Vectors (lists) while(tokens.nextToken() != tokens.TT_EOF) {// TT_EOF a system constant int x = (int) tokens.nval; tokens.nextToken(); int y = (int) tokens.nval; tokens.nextToken(); int z = (int) tokens.nval; tokens.nextToken(); System.out.println("read: " + x + " " + y + " " + z); v.addElement(new Movie2(x,y,z)); }; stream.close(); for (int counter = 0; counter < v.size(); counter++) { System.out.println( ((Movie2) (v.elementAt(counter))).rating()); } } }

Vector elements Execution In input2.data: import java.util.Vector; 4 7 9 3 2 6 class Test { 1 1 1 public static void main(String argv[]) { Output: Vector v; /home/vzaychik/cs390/>java vectorExample input2.data v = new Vector(0); java vectorExample input2.data v.addElement(new Integer(1));// creates integer read: 4 7 9 read: 2 6 1 // object v.addElement("abc"); read: 1 1 1 for (int i=0; i

} Anything except a primitive type (int, float, boolean, char) is a subclass of Object.

8