Você está na página 1de 52

Object Oriented Programming

2nd Year
Computer & System Engineering
Department

Dr. Khaled Nagi


WS 2007/08
What is Java?
 Java is a high-level, 3rd generation programming language, like C, Fortran, Smalltalk,
Perl,…
– Java shares much of C's syntax, however, it is not C. Knowing how to program in C may help (or
disturb!) programming in Java!
 Java is a platform for application development
– Java solves the problem of platform-independence by using byte code.
– The Java compiler does not produce native executable code for a particular machine. Instead it
produces a byte code format.
– The Java interpreter then reads the byte code and translates it into the native language of the host
machine on the fly.
– Since the byte code is completely platform independent, only the interpreter and a few native
libraries need to be ported.
– The rest of the runtime environment including the compiler and most of the class libraries are written
in Java.
– All these pieces, the javac compiler, the java interpreter, the Java programming language, and more
are collectively referred to as Java.
What is Java?

 Java is object-oriented programming language.


– In object-oriented programs data is represented by objects.
Objects have two sections, fields (instance variables) and
methods.
 Fields tell what an object is (values of its properties).
 Methods tell what an object does.(behavior of object)
– When a program is run messages are passed back and
forth between objects.
– When an object receives a message it responds accordingly
as defined by its methods.
Differences between Java and C++

 Global variables:
– These are discouraged in Java. It is impossible to create a global
variable that is outside of all classes. The only way to create a
global variable is by declaring public static variable in a class.
 GOTO:
– Java has no goto statement. It reserves the goto keyword to cover
the only sensible uses of it.
 Pointers:
– Java has no way to manipulate pointers (mem addresses) directly.
You cannot convert an integer to a pointer, you cannot
dereference an arbitrary memory address.
Differences between Java and C++

 Memory Allocation:
– Java has no malloc() or free() functions. Since every complex data
structure is an object, they are all allocated memory via the new
operator. As soon as there is no reference of any kind to an object,
it is collected- automatically - for reuse by the system (garbage
collection/ recycle).
 Data types:
– Hardware-dependent data types such as int and char* lead to non-
portable code. Java uses a standard size irrespective of the H/W.
 No header files.
 No preprocessor.
Differences between Java and C++

 Java does not have an explicit link phase.


– Java source code is divided into .java files (called compilation
units). The compiler compiles these into .class files containing byte
code.
– Exactly one .class file is produced for each class definition.
– The compiler searches the current directory and directories
specified in the CLASSPATH environment variable to find other
classes explicitly referenced by name in each source code file.
– Classes that were unknown to a program when it was compiled
can be loaded into it at runtime.
 Java is inherently multi-threaded.
– A single Java program can have many different threads executing
independently and continuously.
The Hello World Application
// Example Java program… (single line comment)
/* This is a multi-line comment
Type this program using text (ASCII) editor, save it under the name
“HelloWorld.java”, then compile it using ‘javac HelloWorld.java’. This will
produce HelloWorld.class file which can be run using ‘java HelloWorld’
*/
class HelloWorld {
public static void main (String args[]) {
System.out.println("Hello World!");
}
}

 Java is case sensitive.


 Java is a free-form language.
Hello World!
 White spaces separate tokens.
Javadoc… Documentation
 javadoc is a tool to extract special comment tags in Java programs.
 The output of javadoc is an HTML file.
 All of the javadoc commands occur only within /** and */.
 There are two primary ways to use javadoc:
– embed HTML, or
– use “doc tags.”
 Doc tags are commands that start with a ‘@’ and are placed at the
beginning of a comment line. (A leading ‘*’, however, is ignored.)
 There are three “types” of comment documentation, which correspond
to the element the comment precedes: class, variable, or method.
Javadoc… Documentation
//HelloWorld.java
/** The first example program. Class comment,
* Displays a string “Hello World!”. precedes the class
* @author your-name definition
* @author www.company.com
* @version 2.0
*/
public class HelloWorld {
/** Sole entry point to class & application Method
* @param args array of string arguments comment,
* @return No return value precedes
* @exception exceptions No exceptions thrown the method
* @see System.out definition
*/
public static void main(String[] args) {
System.out.println("Hello World!");
}
Hyperlink!
}
Reserved Keywords
Java Programming Style

 In Java, every thing is an object.


– You manipulate an object using a reference to it
(identifier).
– You create an object by first create a reference.
– If you do not initialize it when created, the Java
compiler will put the reference = “null”.
 Identifiers in Java are case sensitive and only $ and
_ special characters are allowed.
Java Programming Style

 Naming conventions
– public methods and variables have a leading lowercase
(nextItem, currentValue, getTime)
– private and local identifiers have lower case with mixed
underscore (next_time, current_value, temp_position)
– final variables that represent contants use all upper case
(GREEN, FRIDAY, MAXSTUDENT)
– class names starts with upper case (String, HelloWorld,
MaterialClass)
Special case: Primitive Types

 “primitive” types that we use quite often in


programming have special treatment. They are
“automatic” variables not reference. (i.e. not objects)
 The variable holds the value, and it is placed on the
stack so it’s much more efficient than using new.
 Java determines the size of each primitive type.
These sizes don’t change from one machine
architecture to another as they do in most
languages.
 All numeric types are signed.
Primitive Types
Literals -- Examples
Special Escape Sequence
Variables

 A variable is defined by the combination of an identifier, a type


and a scope.
type identifier [=value][, identifier [=value]…];
 Java variables are valid only from the point where they are
declared till the end of the enclosing compound statement.
 No variable hiding is allowed.
 Automatic type conversion is done when widening or
promotion. However, narrowing must explicitly be done.
int i; byte b = 100; i = b; -------Automatic
int i =100; byte b = (byte)i; ----Explicit
Arrays
 Array type is orthogonal to the type system.
 Arrays are always initialized and range checking is done at run-time.
 Array objects have intrinsic length member variable.
 Multidimensional arrays can have variable lengths.
 Examples:

int [] month_days; //int month_days[]; int [][]var_matrix;


month_days = new int[12]; var_matrix = new int [4][];
month_days[0] = 31; var_matrix[0]= new int [5];
month_days[1] = 28; var_matrix[1]= {10,20,30};
… var_matrix[2]= new int [7];
month_days[11] = 31; var_matrix[3]= new int [10];

int [] month_days = {31,28,31,30,31,30,31,31,30,31,30,31};


Operators
 An operator takes one or more arguments and produces a
value. It may modifies its arguments (side effect)
 Almost all operators work only with primitives.
– The exceptions are ‘=’,‘==’ and ‘!=’, which work with all objects
(reference to objects).
– the String class supports ‘+’ and ‘+=’.
 Assignment operator for objects are called “aliasing”
 To compare contents of objects use the special method
equals() that exist with every object.
– You must override it to function correctly, otherwise the default
works with the reference.
Operators
 Shift operators and bit-wise logical operators work only for
primitive integral types.
– If you shift a char, byte, or short, it will be promoted to int before
the shift takes place, and the result will be an int. Only the five
low-order bits of the right-hand side will be used.
– If you’re operating on a long, you’ll get a long result. Only the six
low-order bits of the right-hand side will be used.
 Ternary if-else operator (?:)
– boolean-exp ? value0 : value1
 The sole place that the comma operator is used in Java is in for
loops.
 Java has no sizeof() operator.
Execution Control

 if-else
if (Boolean-expression) statement [else statement]
 return
 Iteration
while(Boolean-expression) statement
do statement while(Boolean-expression);
for(initialization; Boolean-expression; step) statement
 Example:
for(int i = 0, j = 1; i < 10 && j != 11; i++, j++)
 Inside the body of any of the iteration statements you can
control the flow of the loop by using break and continue.
Execution Control

 switch(integral-selector) {
case integral-value1 : statement; [break;]
case integral-value2 : statement
statement; [break;]
case integral-value3 : statement; [break;]
case integral-value4 : statement; [break;]
case integral-value5 : statement; [break;]
// ...
default: statement;
}
 switch is “fall through”
Classes

 A class is the basic element in OOPs. It defines the


shape and behavior of an object.
 A constructor is a special method that is called
automatically upon creating an object. It returns
nothing.
 The name of the constructor method must match the
name of the class.
 If you define no constructors, the compiler will make
one for you (default constructor).
 More than one constructor can be defined as long as
their signatures are different.
This Keyword

 The this keyword usually means the “current object”


– A can be used only inside a method.
– produces the reference to the object the method has been
called for.
 When used in a constructor followed by an argument
list, it is an explicit call to the specified constructor.
 Can be used to refer to member data when
parameters have the same name as a member data.
Example
class Point{ class Point3D extends Point{
int x,y; int z;
Point(int x, int y){ Point3D(int x, int y, int z){
this.x = x; super(x,y);
this.y = y; this.z = z;
} }
double distance(int x, int y){ double distance(int x, int y, int z){
int dx = this.x – x; int dx = this.x – x;
int dy = this.y – y; int dy = this.y – y;
return Math.sqrt(dx*dx + dy*dy); int dz = this.z – z;
} return Math.sqrt(dx*dx + dy*dy + dz*dz);
double distance(Point p){ }
return distance(p.x, p.y); double distance(Point3D p){
} return distance(p.x, p.y, p.z);
} }
double distance(int x; int y){
double dx = this.x/z – x;
double dy = this.y/z – y;
return Math.sqrt(dx*dx + dy*dy);
}
}
Example
class PointDistance {
public static void main(String args[]) {
Point3D p1 = new Point3D(30,40,10);
Point3D P2 = new Point3D(0,0,0);
Point p = new Point(4,6);
System.out.println(“p1= “ + p1.x + “,”+ p1.y + “,”+ p1.z);
System.out.println(“p2= “ + p2.x + “,”+ p2.y + “,”+ p2.z);
System.out.println(“p= “ + p.x + “,” + p.y);
System.out.println(“p1.distance(p2) = “ + p1.distance(p2));
System.out.println(“p1.distance(4,6) = “ + p1.distance(4,6));
System.out.println(“p1.distance(p) = “ + p1.distance(p));
}
} Method overriding
Dynamic binding
p1= 30,40,10
p2= 0,0,0
Output p= 4,6
p1.distance(p2) = 50.99019513592785
p1.distance(4,6) = 2.23606797749979
p1.distance(p) = 2.23606797749979
Dynamic Method Dispatch
class A {
void callme() {
System.out.println(“A”);
}
}
class B extends A{
void callme() {
System.out.println(“B”);
}
}
class Dispatch{
public static void main(String args[]){
A a = new B();
a.callme();
}
}
final

 final is a type modifier used to declare that


subclasses are no longer allowed to override the
variable or method.
 final variables are the same as static and usually
used to create the equivalent of const in C++.
– Example
final int RED=1;
final int GREEN=2;
 final methods prevents subclasses from overriding
the method.
static

 static variables are treated as global within


the class. It needs no object to access.
 static methods can be called outside the
context of any instance.
 static blocks gets executed exactly once
when the class is first loaded.
class StaticExample{
static int a = 3;
static int b;
static void method(int x){
system.out.println(“x= “+x);
system.out.println(“a= “+a);
system.out.println(“b= “+b);
}
static {
system.out.println(“static block initialized”);
b=a*4;
}
public static void main(String args[]){
method(42);
}
}
abstract

 The abstract keyword is used to declare “subclasser


responsibility” for methods implementations.
 An abstract class will define the structure of some
methods without providing the implementation.
– Any class which contains any abstract method, must also
declared abstract.
– No direct instantiation of abstract class with the new
operator.
– No abstract constructors or abstract static methods.
– Any subclass of an abstract class must either implement all
of the abstract methods in the superclass, or be itself
declared abstract.
abstract
abstract class A{
abstract void callme();
void metoo(){
System.out.println(“inside A’s metoo method”);
}
}
class B extends A{
void callme(){
System.out.println(“inside B’s callme method”);
}
}
class TestAbsract{
public static void main(String args[]){
A a=new B();
a.callme();
a.metoo();
}
}
package & import Statements
 Packages are containers for classes that are used to manage the
class name space.
 Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
 Java compiler uses file system directories to store packages.
– If you declare a class to be inside of a package, then the source file for that
class must be stored in a directory with the same name as the package.
 The general form of a java source file is
[package pkg1[.pkg2[…]]];
[import pkgr[.pkgt[…]][.class_name|*]];
...
[import pkgn[.pkgm[…]][.class_name|*]];
A single public class declaration;
[any number of private class definition];
package & import Statements

 If package statement is not present, then all the classes end up


in the default package which has no name.
 The import statement are used to bring certain classes, or
entire packages into direct visibility.
 import java.lang.*; is implicitly considered at the top of all
programs.
 If a class with the same name exists in two different imported
packages, the compiler dictates that explicit naming must be
used.
 CLASSPATH environment variable defines the root of all java
packages.
Access Protection
interface & implements Statements

 interface is the mechanism which is used to disconnect the


definition of methods from the class hierarchy.
– interfaces are just like classes, but usually without instance
variables and with methods declared without any body (like
abstract).
– If you declare variables in an interface, they will be treated as final
constants.
– If an interface contains no methods, then any class which declares
that it implements such an interface is actually importing the
constant variables into the class name space as final variables.
 Classes may implement any number of interfaces.
– A class implements an interface by implementing each method in
the interface.
interface & implements Statments
interface Packable{ public byte[] pack(){
byte[] pack(); byte[] ret = new byte[8];
void unpack(byte b[]); ret[0] = p(x,24); ret[4] = p(y,24);
} ret[1] = p(x,16); ret[5] = p(y,16);
class Point{ ret[2] = p(x,8); ret[6] = p(y,8);
int x,y; ret[3] = p(x,0); ret[7] = p(y,0);
Point(int x, int y){ return ret; }
this.x = x; public void unpack(byte[] b){
this.y = y; x=u(b[0],24)|u(b[1],16)|u(b[2],8)|u(b[3],0);
} y= u(b[4],24)|u(b[5],16)|u(b[6],8)|u(b[7],0); }
} public String toString(){
class NewPoint extends Point implements Packable{ return “NewPoint[“ + x + ”,” + y + ”]”; }
NewPoint(int x; int y){ }
super(x,y); class PointPack{
} public static void main(String args[
NewPoint(){ Packable p=new NewPoint(123456, 214748);
this(0,0); byte[] packed = p.pack();
} NewPoint p1 =new NewPoint();
private byte p(int t, int n){ p1.unpack(packed);
return (byte)((t>>n)&0xff); System.out.println(packed + “=“ + p1;}
}
private int u(byte b, int n){
return (b&0xff)<<n;
}
Sample of Java Classes:

String and StringBuffer


 String and StringBuffer classes are built-in
classes in java.lang package
– String represents unchangeable strings.
– StringBuffer is a companion class that represents
objects of strings that can be manipulated after
creation.
Sample of Java Classes:

 Constructors
– String s = new String(); //creates empty string
– char ch[] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}
– String s = new String(ch); //creates “abcdef”
– String s1 = new String(ch,2,3); // creates “cde”
– byte ascii[]={65,66,67,68,69,70};
– String s2 = new String(ascii,0); //”ABCDEF” with hiByte=0
– String s3 = new String(ascii,0,2,3); //” CDE” with hiByte=0
– Special syntax
 String s = “abcd”;
– Member method: length()
 String s = “abcd”; System.out.println(s.length());
Sample of Java Classes:
 Concatenation
– ‘+’ is overloaded
int age;
String s = “He is” + age + “years old”;

int age;
String s = new StringBuffer(“He is”)
.append(age)
.append(“years old”)
.toString();

String conversion:
Every class should override toString() method to get the required representation of
the output.
Sample of Java Classes:

 Character Extraction
String s = “ABCDEF”
char ch = s.charAt(1)
int start = 2;
int end = 5;
char buf[] = new char(end – start);
s.getChars(start, end, buf, 0);
byte bbuf[] = new byte(end – start);
s.getByte (start, end, bbuf, 0); Extracts the chars from
the string and place them
into byte buffer after
dropping the high order
byte.
Sample of Java Classes:
 String Comparison
boolean equals(String s)
boolean equalsIgnoreCase(String s)
boolean regionMatches(int offset, String other, int otheroffset, int len)
boolean regionMatches(boolean ignorecase, int offset, String other, int
otheroffset, int len)
boolean startsWith(String s)
boolean endsWith(String s)
int compareTo(String s)
int indexOf(char ch)
int lastIndexOf(char ch)
………
Note: == is used only to compare two object references
Sample of Java Classes:

 String Copy Modification


Note: Return new string objects
String substring(int start)
String substring(int start, int end)
String concat(String s)
String replace(char current, char newchar)
String toLowerCase()
String toUpperCase()
Exception Handling

 An exception is an abnormal condition that arises in a code


sequence at run time.
 A java exception is an object that describes an exceptional
condition.
 Exceptions can appear asynchronously in a method, or they
can be explicitly created and thrown to report some error
condition to the calling method.
 If you’re inside a method and you throw an exception (or
another method you call within this method throws an
exception), that method will exit in the process of throwing.
 If you don’t want a throw to exit the method, you can set up a
special “try” block within that method to catch the exception.
General Form of Exception Handling
Block

try{
//block of code
} catch(ExceptionType1 e){
// exception handler for ExceptionType1
}catch(ExceptionType2 e){
// exception handler ExceptionType2
throw(e); // rethrow the exception

}finally {
// finally code
}
Main Exception Types
How Exception Works
 When java runtime tries to execute the code of try block, and an
abnormal condition occurs, the runtime stops the code and throws an
exception object of the type representing the condition (error).
 The flow of code execution is interrupted and the current call-stack is
searched for any compatible exception handler.
 If no exception handler is found, the default handler is used which
prints out the Exception object and the stack trace of where the
exception occurred.
 The scope of the catch clause is restricted to the immediately
preceding try statement.
 The throw statement is used to explicitly throw an exception. The flow
of execution stops immediately after the throw statement, and the next
statement is not reached. The corresponding handler is executed.
Exception Specification (throws)

 To identify the list of possible exceptions that a


method might throw, the compiler dictating the use of
the keyword throws.
type method-name(arg-list) throws exception-list{}
 For all Exception subclasses, you have to declare
which types a method will possibly throw.
 For Error or RuntimeException, the above rule does
not apply.
finally

 The finally keyword is used to identify a block


of code that will always run no matter an
exception is thrown and whether it is caught
or not.
 The finally block will be executed just before
a method returns to the caller.
 The finally block is used to perform clean-up
tasks (destructor).
The finally clause is always executed.

class ThreeException extends Exception {}


public class FinallyWorks { ThreeException
static int count = 0; In finally clause
public static void main(String[] args) { No exception
while(true) { In finally clause
try {
if(count++ == 0) throw new ThreeException();
System.out.println("No exception");
} catch(ThreeException e) {
System.err.println("ThreeException");
} finally {
System.err.println("In finally clause");
if(count == 2) break; // out of "while"
}
}
}
}
Example
class FinallyDemo{
static void procedureA(){
try{ System.out.println(“inside A”);
throw new RuntimeException(“Demo”);
} finally {System.out.println(“A’s finally”);}
}
static void procedureB(){
try{System.out.println(“inside B”);
return;
} finally {System.out.println(“B’s finally”);}
}
public static void main(String args[]){ inside A
try{ procedureA(); A’s finally
} catch (Exception e){; java.lang.RuntimeException: Demo
System.out.println(e);} inside B
procedureB(); B’s finally
}
}
Exercise

 Write a complete java code that illustrates


the various outcomes of code flow when
– Catching an exception inside the method.
– Catching an exception in a higher level.
– No catching of the exception.
– No exception generated.
 Your code should contain finally block.

Você também pode gostar