Object Oriented Programming
OOP In Java
Lecture #01
Prof- Maqsood Ahemd Razi
Different Programming Paradigms
• Functional/procedural programming:
– program is a list of instructions to the computer
• 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
• object holds values of its class’s attributes
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”
What does it buy us ?
• Modularity
– source code for an object can be written and maintained
independently of the source code for other objects
– easier maintainance and reuse
• 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
Java Virtual Machine
• Unlike other languages, Java “executables”
are executed on a CPU that does not exist.
Platform Dependent
myprog.c myprog.exe
gcc machine code
C source code
OS/Hardware
Platform Independent
myprog.java myprog.class
javac bytecode
Java source code
JVM
OS/Hardware
Primitive types
• int 4 bytes
• short 2 bytes
• long 8 bytes
Behaviors is
exactly as in
• byte 1 byte
C++
• float 4 bytes
• double 8 bytes
• char Unicode encoding (2 bytes) Note:
Primitive type
• boolean {true,false} always begin
with lower-case
Primitive types - cont.
• Constants
37 integer
37.2 float
42F float
0754 integer (octal)
0xfe integer (hexadecimal)
Wrappers
Java provides Objects which wrap
primitive types and supply methods.
Example:
Integer n = new Integer(“4”);
int m = n.intValue();
Read more about Integer in JDK Documentation
Hello World
Hello.java
class Hello {
public static void main(String[] args) {
System.out.println(“Hello World !!!”);
}
}
C:\javac Hello.java ( compilation creates Hello.class )
C:\java Hello (Execution on the local JVM)
More sophisticated
class Kyle {
private boolean kennyIsAlive_;
Default public Kyle() { kennyIsAlive_ = true; }
C’tor public Kyle(Kyle aKyle) {
kennyIsAlive_ = aKyle.kennyIsAlive_;
}
public String theyKilledKenny() {
if (kennyIsAlive_) {
Copy
kennyIsAlive_ = false;
C’tor 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 ( to execute )
Kyle: You bastards !!!
Arrays
• Array is an object
• Array size is fixed
Animal[] arr; // nothing yet …
arr = new Animal[4]; // only array of pointers
for(int i=0 ; i < arr.length ; i++) {
arr[i] = new Animal();
// now we have a complete array
Arrays - Multidimensional
• In C++
Animal arr[2][2]
Is:
• In Java
Animal[][] arr=
new Animal[2][2]
What is the type of
the object here ?
Static - [1/4]
• Member data - Same data is used for all the
instances (objects) of some Class.
Assignment performed
Class A {
on the first access to the
public int y = 0;
Class.
public static int x_ = 1;
Only one instance of ‘x’
};
exists in memory
A a = new A();
A b = new A(); a b
System.out.println(b.x_); Output: 0 0
a.x_ = 5; y y
System.out.println(b.x_);
A.x_ = 10;
1
System.out.println(b.x_); 5 1
10 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_; }
}
Static - [2/4] cont.
Usage:
TeaPot tp1 = new TeaPot(Color.RED);
TeaPot tp2 = new TeaPot(Color.GREEN);
System.out.println(“We have “ +
TeaPot.howManyTeaPots()+ “Tea Pots”);
Static - [3/4]
• Block
– Code that is executed in the first reference to the class.
– Several static blocks can exist in the same class
( Execution order is by the appearance order in the class
definition ).
– Only static members can be accessed.
class RandomGenerator {
private static int seed_;
static {
int t = System.getTime() % 100;
seed_ = System.getTime();
while(t-- > 0)
seed_ = getNextNumber(seed_);
}
}
}
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”);
• The String object is a constant. It can’t be changed using
a reference to it.
Flow control
Basically, it is exactly like c/c++.
do/while
int i=5; switch
if/else do { char
If(x==4) { // act1 c=IN.getChar();
// act1 i--; switch(c) {
} else { } while(i!=0); case ‘a’:
// act2 case ‘b’:
} for // act1
break;
int j;
default:
for(int i=0;i<=9;i++)
// act2
{
}
j+=i;
}
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
• default ( if no access modifier stated )
– Usually referred to as “Friendly”.
– Can be called/modified/instantiated from the same package.
class Base {
Inheritance Base(){}
Base(int i) {}
protected void foo() {…}
}
Base
class Derived extends Base {
Derived() {}
protected void foo() {…}
Derived(int i) {
super(i);
Derived …
super.foo();
}
}
As opposed to C++, it is possible to inherit only from ONE class.
Pros avoids many potential problems and bugs.
Cons might cause code replication
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