Modern Compiler Design Java Tutorial
Modern Compiler Design Java Tutorial
Java Tutorial
Object-Oriented Programming
Object-oriented programming
program is composed of a collection objects
that communicate with each other
Main Concepts
Object
Class
Inheritance
Encapsulation
Objects
identity unique identification of an object
attributes data/state
services methods/operations
supported by the object
within objects responsibility to provide these
services to other clients
Class
type
object is an instance of class
class groups similar objects
same (structure of) attributes
same services
Inheritance
Class hierarchy
Generalization and Specialization
subclass inherits attributes and services from its
superclass
subclass may add new attributes and services
subclass may reuse the code in the superclass
subclasses provide specialized behaviors (overriding
and dynamic binding)
partially define and implement common behaviors
(abstract)
Encapsulation
Separation between internal state of the object
and its external aspects
How ?
control access to members of the class
interface type
Information hiding
other objects can ignore implementation details
security (object has control over its internal state)
but
shared data need special design patterns (e.g., DB)
performance overhead
Why Java ?
Portable
Easy to learn
[ Designed to be used on the Internet ]
JVM
JVM stands for
Platform Dependent
myprog.c
gcc
C source code
myprog.exe
machine code
OS/Hardware
Platform Independent
myprog.java
javac
myprog.class
bytecode
JVM
OS/Hardware
Primitive types
int 4 bytes
short
2 bytes
long
8 bytes
Behaviors is
byte
1 byte
exactly as in
float
4 bytes
C++
double 8 bytes
char
Unicode encoding (2 bytes)
boolean {true,false}
Note:
Primitive type
always begin
with lower-case
Wrappers
Java provides Objects which wrap
primitive types and supply methods.
Example:
Integer n = new Integer(4);
int m = n.intValue();
Hello World
Hello.java
class Hello {
public static void main(String[] args) {
System.out.println(Hello World !!!);
}
}
C:\javac Hello.java
C:\java Hello
More sophisticated
class Kyle {
private boolean kennyIsAlive_;
Default
public Kyle() { kennyIsAlive_ = true; }
Ctor
public Kyle(Kyle aKyle) {
kennyIsAlive_ = aKyle.kennyIsAlive_;
}
public String theyKilledKenny() {
if (kennyIsAlive_) {
Copy
kennyIsAlive_ = false;
Ctor
return You bastards !!!;
} else {
return ?;
}
}
public static void main(String[] args) {
Kyle k = new Kyle();
String s = k.theyKilledKenny();
System.out.println(Kyle: + s);
}
}
Results
javac Kyle.java
( to compile )
java Kyle
Kyle: You bastards !!!
( to execute )
Arrays
Array is an object
Array size is fixed
Arrays - Multidimensional
In C++
Animal arr[2][2]
Is:
In Java
Animal[][] arr=
new Animal[2][2]
Static - [1/4]
Member data - Same data is used for all the
instances (objects) of some Class.
Assignment performed
on the first access to the
Class.
Only one instance of x
exists in memory
Class A {
public int y = 0;
public static int x_ = 1;
};
A a = new A();
A b = new A();
System.out.println(b.x_);
a.x_ = 5;
System.out.println(b.x_);
A.x_ = 10;
System.out.println(b.x_);
a
Output:
1
5
10
0
y
b
0
y
1
A.x_
Static - [2/4]
Member function
Static member function can access only static members
Static member function can be called without an
instance.
Class TeaPot {
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }
// error :
public static Color getColor()
{ return myColor_; }
}
Block
Static - [3/4]
String is an Object
Constant strings as in C, does not exist
The function call foo(Hello) creates a String object,
containing Hello, and passes reference to it to foo.
There is no point in writing :
String s = new String(Hello);
Flow control
Basically, it is exactly like c/c++.
do/while
if/else
If(x==4) {
// act1
} else {
// act2
}
int i=5;
do {
// act1
i--;
} while(i!=0);
for
int j;
for(int i=0;i<=9;i++)
{
j+=i;
}
switch
char
c=IN.getChar();
switch(c) {
case a:
case b:
// act1
break;
default:
// act2
}
Packages
Java code has hierarchical structure.
The environment variable CLASSPATH contains
the directory names of the roots.
Every Object belongs to a package ( package
keyword)
Object full name contains the name full name of the
package containing it.
Access Control
public member (function/data)
Can be called/modified from outside.
protected
Can be called/modified from derived classes
private
Can be called/modified only from the current class
Inheritance
Base
Derived
class Base {
Base(){}
Base(int i) {}
protected void foo() {}
}
class Derived extends Base {
Derived() {}
protected void foo() {}
Derived(int i) {
super(i);
super.foo();
}
}
Polymorphism
Inheritance creates an is a relation:
For example, if B inherits from A, than we say that
B is also an A.
Implications are:
access rights (Java forbids reducing access rights) derived class can receive all the messages that the base
class can.
behavior
precondition and postcondition
Inheritance (2)
In Java, all methods are virtual :
class Base {
void foo() {
System.out.println(Base);
}
}
class Derived extends Base {
void foo() {
System.out.println(Derived);
}
}
public class Test {
public static void main(String[] args) {
Base b = new Derived();
b.foo(); // Derived.foo() will be activated
}
}
Abstract
abstract member function, means that the function does not have an implementation.
abstract class, is class that can not be instantiated.
AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
new AbstractTest();
^
1 error
NOTE:
An abstract class is not required to have an abstract method in it.
But any class that has an abstract method in it or that does
not provide an implementation for any abstract methods declared
in its superclasses must be declared as an abstract class.
Example
Abstract - Example
package java.lang;
public abstract class Shape {
public abstract void draw();
public void move(int x, int y) {
setColor(BackGroundColor);
draw();
setCenter(x,y);
setColor(ForeGroundColor);
draw();
}
}
package java.lang;
public class Circle extends Shape {
public void draw() {
// draw the circle ...
}
}
Interface
Interfaces are useful for the following:
Capturing similarities among unrelated
classes without artificially forcing a class
relationship.
Declaring methods that one or more classes
are expected to implement.
Revealing an object's programming interface
without revealing its class.
Interface
abstract class
Helps defining a usage contract between classes
All methods are public
Javas compensation for removing the multiple
inheritance. You can inherit as many interfaces
as you want.
- The correct term is to implement
an interface
*
Example
Interface
interface IChef {
void cook(Food food);
}
interface BabyKicker {
void kickTheBaby(Baby);
}
interface SouthParkCharacter {
void curse();
}
SouthParkCharacter {
MUST be public
}
f) { }
Collections
Collection/container
object that groups multiple elements
used to store, retrieve, manipulate, communicate
aggregate data
Collection Interfaces
Collection
Set
SortedSet
List
Map
Queue
Sorted Map
Collection Interface
Basic Operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element);
boolean remove(Object element);
Iterator iterator();
Bulk Operations
Array Operations
Object[] toArray(); <T> T[] toArray(T[] a); }
List
Map
Queue
Sorted Map
SortedSet
HashSet
TreeSet
ArrayList LinkedList
TreeMap HashMap
final
final member data
Constant member
final member function
The method cant be
overridden.
final class
Base is final, thus it
cant be extended
(String class is final)
final
Derived.java:6: Can't subclass final classes: class Base
class class Derived extends Base {
^
1 error
IO - Introduction
Definition
Stream is a flow of data
characters read from a file
bytes written to the network
Philosophy
All streams in the world are basically the same.
Streams can be divided (as the name IO suggests) to Input and
Output streams.
Implementation
Incoming flow of data (characters) implements Reader (InputStream for
bytes)
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;