Introduction
to Java
• Short Introduction to the Concepts
of Programming in Java
• Overview over the most important
constructs
OOIS 1998/99 Ulrike Steffens Software Systems Institute
ul. steffens @tu- harburg .de http:// www.sts.tu- harburg .de
Data Types
• Two different kinds of data types – primitive types – reference types
Primitive Types
• boolean • char • int • longOOIS-11-98-StWe-Java 3
Reference Types
• Predefined or user-defined Classes • String
• Array
• The values of reference types are not manipulated directly.
• Instead handles (references) to the actual values are used.
a b
0 0
Reference Type Variables
• A variable of a reference type contains a reference to an anonymous object in storage.
Point a,b;
• An uninitialized variable contains a null-reference. • Objects are anonymous.
• They have an immutable identity. • Objects are created at run-time.
OOIS-11-98-StWe-Java 5 a b 0 0 3 4 a b 0 0 3 4
Binding Reference Type Variables
• Assigning an object to a reference type variable, thevariable gets a reference to the object as new value. • The value of the object does not change
a = new Point(0,0); b = new Point(3,4); • Assigning values of other
variables means assigning the references! a = b
• May be a pitfall, as the object may change
a b 34 3 c a == b a != c
Comparing Objects
• Comparing two reference type variables means comparing the references they contain and, thus, comparing the identity of the referenced objects.
OOIS-11-98-StWe-Java 7
Comparing the Contents of Objects
• The contents of objects belonging to pre-defined classes can be compared using the method equals. • If you define a class of your own, equals by default
only compares references, as == does.
• => You have to override equals for new defined classes.
Creating New Data Types: class
• Class keyword defines new data typeclass ATypeName { /* class body goes here */} ATypeName a = new ATypeName ();
• Fields class DataOnly { int i; float f; boolean b; }
• Each instance of DataOnly gets its own copy of the fields
OOIS-11-98-StWe-Java 9
Methods, Arguments and Return
Values
• Methods: how you get things done in an object – Traditionally called “functions”
– Can only be defined inside classes
returnType methodName (/*argument list */){ /* method body */
}
• Example method call:
int x = a.f(); // For object a
The Argument List
• Types of the objects to pass in to the method • Name (identifier) to use for each one
• Whenever you seem to be passing objects in Java, you‘re actually passing handles
int size(String s){ return s.length (); }
OOIS-11-98-StWe-Java 11
Control Flow Statements
• if (condition) {...} else {...} • (condition) ? value1: value2
• while (condition) {...}
• do {...} while (condition)
• for(int i = 0; i < 10; i++) {...}
• switch(value ){ case (value1): ... ; case (value2): ... ; ... default: ...; }
The “static” Keyword
• Normally each object gets its own data
• What if you want only one piece of data shared between all objects of a class? (“class data”)
class StaticTest { static int i = 47; }
• What if you want a method that can be called for the class, without an object? (“class method”)
class StaticFun {
static void incr () { StaticTest .i++; } }
OOIS-11-98-StWe-Java 13
Guaranteed Initialization with the
Constructor
class Rock {
Rock() { // This is the constructor System. out.println ("Creating Rock"); }
}
public class SimpleConstructor {
public static void main(String args[]) {
for(int i = 0; i < 10; i++) new Rock();
} }
Nuance
• We can deduce meaning from context “Wash the shirt”
“Wash the car” “Wash the dog”
Not “shirtWash the shirt” “carWash the car” “dogWash the dog”
OOIS-11-98-StWe-Java 15
Method Overloading
void wash (shirt s) { // ... void wash (car c) { // ... void wash (dog d) { // ...
Unique argument combinations distinguish overloaded methods
Method Overloading
• One word, many meanings: overloaded class Tree {
int height ; Tree () {
System. out.println ("A seedling "); height = 0;
}
Tree (int i) {
System. out.println ("A new Tree , " + i + " feet tall ");
height = i; }
OOIS-11-98-StWe-Java 17 void info () {
System. out.println ("Tree is " + height + " feet tall ");
}
void info (String s) {
System. out.println (s + ": Tree is “ + height + " feet tall "); }
}
Default Constructor:
Takes no Arguments
• Compiler creates one for you if you write no constructors
class Bird { int i; }
public class DefaultConstructor {
public static void main (String args []) { Bird nc = new Bird (); // default !
OOIS-11-98-StWe-Java 19
this
: Handle to Current Object
public class Leaf {private int i = 0; Leaf increment () { i++; return this; } void print () {
System. out.println ("i = " + i); }
public static void main (String args []) { Leaf x = new Leaf ();
x. increment ().increment ().increment ().print (); }
}
this in Constructors
• A very common kind to use this is in constructors to initialize data fields with the constructor's arguments
public class Animal {
private int numberOfLegs ; Animal(int numberOfLegs ) {
this. numberOfLegs = numberOfLegs ; }
OOIS-11-98-StWe-Java 21
Overloading on Return Values
• Why not also use return values in method overloading?
void f() { // ... int f() { // ...
• Then what would this mean? f();
Member Initialization
void f() { int i; // No initialization i++; }• Produces compile-time error
• Inside class, primitives are given default values if you don’t specify values
class Data { int i = 999;
OOIS-11-98-StWe-Java 23
Array Initialization
int a1[]; // this ...
int[] a1; // is the same as this ! • Creates a handle, not the array. Can’t size it. To
create an array of primitives:
int a1[] = { 1, 2, 3, 4, 5 }; • An array of class objects:
Animal a[] = new Animal [20]; // 20 x null System. out.println (a.length + " animals "); for(int i = 0; i < a. length ; i++) {
a[i] = new Animal ((i % 2 + 1) * 2); }
• Bounds checked, length produces size
Array Initialization
• Can also use bracketed list (The size is then fixed at compile-time) Integer[] a = { new Integer(1), new Integer(2), new Integer(3), };
• If you do anything wrong either the compiler will catch it or an exception will be thrown
OOIS-11-98-StWe-Java 25
Multi-dimensional Arrays
• It is possible to define multi-dimensional arrays in the same way as described.
int[][] a;
• The brackets even may be distributed between type and identifier.
int[] a[];
• Initialization can be done directly
int[][] a = { { 1, 2, 3 }, { 5, 6} };
• It can also be done by nested iterations over the array and its components.
• arrays may not be rectangular
Strings
• Strings are immutable objects of the class String. • String literals are zero, one or more characters
included within double quotes.
• When a binding to a string literal is executed for the first time, a new String object is created.
• If any other bindings to this literal appear, the respective variables will hold reference to the same object.
OOIS-11-98-StWe-Java 27 "abc" a b c "abc"
String Constructors
• String objects can also be created by calling a constructor.
• String constructors create new objects whenever they are called.
String c = new String(" abc");
• There are several constructors defined for strings.
String Concatenation
• Strings can be concatenated by using +. String c = "A " + "concatenation";
• The concatenation also creates a new String object. • Values of other types can be concatenated to strings,
too.
• They are implicitly converted to String. String n = "Number " + 49;
OOIS-11-98-StWe-Java 29
Package:
the Library Unit
import java .util .*; import java .util .Vector ; • Managing “name spaces”– Class members are already hidden inside class – Class names could clash
– Need completely unique name • Compilation units (.java files)
– Name of .java file == name of single public class – Other non-public classes are not visible
– Each class in file gets its own .class file
– Program is a bunch of .class files (no .obj or .lib)
Creating a Library of Classes
package mypackage ;– public class is under the umbrella mypackage
– Client programmer must import mypackage.*;
• Creating unique package names
– Location on disk encoded into package name – Convention: first part of package name is Internet
domain name of class creator (reversed)
OOIS-11-98-StWe-Java 31
Library Location
C:\DOC\Java\ SomeDirectory \util • CLASSPATH takes care of first part:
CLASSPATH=.;D:\JAVA\LIB;C:\DOC\ JavaT • Programs can be in any directory
import SomeDirectory .util .*; public class LibTest {
public static void main (String args []) { Vector v = new Vector ();
List l = new List(); }
}
• Compiler starts search at CLASSPATH
Java Access Control
Interface Access
Only Accessible Within the class
“Sort of private“
public
private
OOIS-11-98-StWe-Java 33
“Friendly”
• Default access, has no keyword
• public to other members of the same package, private to anyone outside the package.
• Easy interaction for related classes (that you place in the same package)
• Also referred to as “package access”
public: Interface Access
package c05. dessert ;public class Cookie { public Cookie () {
System. out.println ("Cookie constructor "); }
void foo () { System. out.println ("foo"); } }
// Separate file : import c05. dessert .*; public class Dinner { public Dinner() {
OOIS-11-98-StWe-Java 35
private: Can’t Touch That!
class Sundae {
private Sundae () {}
static Sundae makeASundae () { return new Sundae ();
} }
public class IceCream {
public static void main (String args []) { //! Sundae x = new Sundae ();
Sundae x = Sundae .makeASundae (); }
}
protected
• Finer grained, deals with inheritance • Generally: when you need it, you’ll know
OOIS-11-98-StWe-Java 37
An Object has an Interface
• Object : Characteristics and Behavior
• Object Creation: Light lt = new Light ();
• Message: lt.on();
That‘s programming with objects! Light on() off() brighten() dim() Interface Type name
Inheritance
• Inheritance: Automatically duplicates the interface Line draw() erase() Shape draw() erase() Circle draw() erase() Square draw() erase()OOIS-11-98-StWe-Java 39 public class Shape {
public void draw() { /* code drawing a shape */} public void erase() { /* code erasing a shape */} }
public class Circle extends Shape{
public void erase() { /* code erasing a circle */} }
Line Shape
Circle Square ... works with all this objects One piece of code ...
Polymorphism
draw() erase ()
OOIS-11-98-StWe-Java 41
An Amazing Trick
void doStuff (Shape s) { s.erase ();
...
s.draw (); }
Circle c = new Circle (); Triangle t = new Triangle (); Line l = new Line ();
doStuff (c); // “ dynamic binding ” doStuff (t); doStuff (l);
Composition vs. Inheritance
Car Wheel [] Window[] Door [] Engine Pure composition: Code reuse Shape draw() erase () Circle draw() erase () Sqare draw() erase () Line draw() erase () Pure inheritance: interface duplication UsefulOOIS-11-98-StWe-Java 43
An
abstract
Instrument
• Abstract classes leave some part of the implementation open
• Some methods and data may only be defined
abstract class Instrument4 {
int i; // storage allocated for each public abstract void play ();
public String what () { return "Instrument4"; }
public abstract void adjust (); }
• Rest of the code is the same…
• Abstract classes cannot be instantiated by new
An Instrument
interface
• No “concrete” elements in interface • You don’t extend, you implement
interface Instrument {
void play (); // Automatically public String what();
void adjust (); }
class Guitar implements Instrument { public void play () {
System. out. println ("Guitar .play()"); }
public String what() { return " Guitar "; } public void adjust () {}
OOIS-11-98-StWe-Java 45
How to use Java on STS-Sun-Workstations?
• Set the paths PATH and CLASSPATH correctly by typing:
def_jdk12
• Create a file with your source code ending on .java • Compile your code:
javac filename.java
• Run your application java filename