You are on page 1of 51

Object oriented Programing

Lecturer: Wedad Al-Sorori

>date/time< >footer< 1
Lecture1 :Introduction

>date/time< >footer< 2
Outlines

Structured vs OO Programing

Basic terminologies

Why OOP

Design principles of OOP

What is java

Main function

Identifiers

Operators

Data types

Variables

06/28/2023 3
STRUCTURED vs. OO PROGRAMMING

Structured Programming

MAIN PROGRAM GLOBAL DATA

FUNCTION FUNCTION 2 FUNCTION 3


1

FUNCTION 4 FUNCTION 5

06/28/2023 4
Structured Programming

Using function

Function & program is divided into modules

Every module has its own data and function which can be called
by other modules.

06/28/2023 5
OBJECT ORIENTED PROGRAMMING

Object 1 Object 2

Data Data

Function Function

Object 3

Data
Function

06/28/2023 6
OBJECT ORIENTED PROGRAMMING

Objects have both data and methods

Objects of the same class have the same data elements and methods

Objects send and receive messages to invoke actions


Key idea in object-oriented:

The real world can be accurately described as a collection of objects that interact.

06/28/2023 7
Basic terminology

object

usually a person, place or thing (a noun)

method

an action performed by an object (a verb)

attribute

description of objects in a class

class

a category of similar objects (such as automobiles)

does not hold any values of the object’s attributes
06/28/2023 8
Basic terminology

An object is a software bundle of variables and related


methods.
Visual Bicycle modeled
representation of a as a software
software object: object:
Basic terminology
A class is a prototype that defines the variables and the
methods common to all objects of a certain kind.

Visual Visual
representation representation
of class: of bike class:
Example for attributes and methods

Attributes: 
Methods:

manufacturer’s name 
Define data items (specify
manufacturer’s name, model,

model name
year, etc.)

year made 
Change a data item (color,

color engine, etc.)

number of doors 
Display data items

size of engine 
Calculate cost

etc. 
etc.

06/28/2023 11
?Why OOP

Save development time (and cost) by reusing code

Once an object class is created it can be used in other applications

Easier debugging

Classes can be tested independently

Reused objects have already been tested

06/28/2023 12
Design Principles of OOP

Four main design principles of Object-Oriented Programming(OOP):


Encapsulation

Abstraction

Polymorphism

Inheritance

06/28/2023 13
Encapsulation

Also known as data hiding

Only object’s methods can modify information in the object.


Analogy:

ATM machine can only update accounts of one person or object only.

06/28/2023 14
Encapsulation
Encapsulation benefits:

Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Also, an object can be easily
passed around in the system.

Information hiding: An object has a public interface that other objects can use to
communicate with it. The object can maintain private information and methods
that can be changed at any time without affecting the other objects that depend
on it.
Encapsulation
Message
Software objects interact and communicate with each other
by sending messages to each other. When object A wants
object B to perform one of B's methods, object A sends a
message to object B
Encapsulation
• The three components of a message:
1) The object to which the message is addressed
(YourBicycle)
2) The name of the method to perform (changeGears)
3) Any parameters needed by the method (lowerGear)
Abstraction

Focus only on the important facts about the problem at hand

to design, produce, and describe so that it can be easily used without knowing
the details of how it works.

Analogy:

When you drive a car, you don’t have to know how the gasoline and air are
mixed and ignited.

Instead you only have to know how to use the controls.

06/28/2023 18
Polymorphism

The same word or phrase can mean different things in different contexts


Analogy:

In English, bank can mean side of a river or a place to put money

06/28/2023 19
Function Overloading

The operation of one function depends on the argument passed to it.

Example: Fly(), Fly(low), Fly(150)

06/28/2023 20
Inheritance

Inheritance—a way of organizing classes

Term comes from inheritance of traits like eye color, hair color, and so on.

Classes with properties in common can be grouped so that their common
properties are only defined once.


Superclass – inherit its attributes & methods to the subclass(es).


Subclass – can inherit all its superclass attributes & methods besides having
its own unique attributes & methods.

06/28/2023 21
Inheritance Example
Inheritance

Superclass

Subclass
Inheritance Example

Superclass 

Vehicle
Subclasses 

Bus
Automobile Motorcycle

Sports Car
Sedan Luxury Bus School Bus

What properties does each vehicle inherit from the types of vehicles
above it in the diagram?

06/28/2023 23
Inheritance
Inheritance benefits:

• Subclasses provide specialized behaviors from the basis of common


elements provided by the superclass. Through the use of inheritance,
programmers can reuse the code in the superclass many times.

• Programmers can implement superclasses called abstract classes


that define "generic" behaviors. The abstract superclass defines and
may partially implement the behavior, but much of the class is
undefined and unimplemented. Other programmers fill in the details
with specialized subclasses.
Object-Oriented Programming Languages

Pure OO Languages

Smalltalk, Eiffel, Actor, Java


Hybrid OO Languages

C++, Objective-C, Object-Pascal

06/28/2023 25
?What is Java

Java is object-oriented with built in Application Programming
Interface (API)

Developed by Sun Microsystems (James Gosling)

It has borrowed its syntax from C/C++

Java does not have pointers directly.

Applications and applets are available.

Java is both compiled and interpreted.

Source code is compiled to bytecode.

The Java Virtual Machine (JVM) loads and links parts of the code dynamically at
run time (late or dynamic binding).

06/28/2023 26
History of Java

Originally for intelligent consumer-electronic devices

Designed for easy Web/Internet applications

Then used for creating Web pages with dynamic content

Now also used for:

Develop large-scale enterprise applications

Enhance WWW server functionality

Provide applications for consumer devices (cell phones, etc.)

06/28/2023 27
History of Java
• 1990 – suggestion in report “Further” concerning creation of new object oriented
environment
• 1991 – OAK (“Object Application Kernel”) language (James Gosling)
• 1995 – new language name: “Java”
• 1996 - Netscape compatible with Java 1.0. Sun propagates Java 1.0 environment
• 2001 – Java 1.4.0 – over 2100 classes library
• 2004 – Java 1.5.0
• 2007 – Java 1.6.0
• .
• .
• .
• .
06/28/2023 28
• 2022 – Java 8
Platform independence of Java

Byte code
Java Byte
• Byte codes are the machine language of the
instruction Cod Java virtual machine.
… code …e
compiler • When a JVM loads a class file, it gets one
stream of byte codes for each method in the
class.

Host • The byte codes streams are stored in the


method area of the JVM.
… system
• The byte codes for a method are executed
when that method is invoked during the
Java virtual Machine course of running the program.
it has an instruction set •
it manipulates various memory • • They can be executed by interpretation, just-
.areas at run time in-time compiling, or any other technique that
was chosen by the designer of a particular
06/28/2023 JVM. 29
:Features of Java
Simple  To follow

Secure  Remote applets are not trusted and not allowed to use local resources

Object-oriented  Supports advantages of OOA

Platform independent and Architecture Neural  Independent form hardware and software platforms

Interpreted  It is complied also and interpreted also.

Robust  Java is strong, replacing pointer by reference and provides automatic memory management

Multi threaded  Supports concurrent procedures

Distributed and Dynamic Supports dynamic binding and links parts of code at the time of execution.

High performance  Java provides native language support

06/28/2023 30
:Features of Java
• Simple
• fixes some clumsy features of C++
• no pointers
• automatic garbage collection
• rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
• Secure
• usage in networked environments requires more security
• memory allocation model is a major defense
• access restrictions are forced (private, public)
:Features of Java
• Object oriented
• focus on the data (objects) and methods manipulating the data
• all functions are associated with objects
• almost all datatypes are objects (files, strings, etc.)
• potentially better code organization and reuse
• Portable (Platform independent and Architecture Neural )
• same application runs on all platforms
• the sizes of the primitive data types are always the same
• the libraries define portable interfaces
:Features of Java
• Interpreted
• java compiler generate byte-codes, not native machine code
• the compiled byte-codes are platform-independent
• java bytecodes are translated on the fly to machine readable instructions in
runtime (Java Virtual Machine)
• Reliable (Robust)
• extensive compile-time and runtime error checking
• no pointers but real arrays. Memory corruptions or unauthorized memory
accesses are impossible
• automatic garbage collection tracks objects usage over time
:Features of Java
• Multithreaded
• multiple concurrent threads of executions can run simultaneously
• utilizes a sophisticated set of synchronization primitives (based on monitors
and condition variables paradigm) to achieve this
• Dynamic
• java is designed to adapt to evolving environment
• libraries can freely add new methods and instance variables without any
effect on their clients
• interfaces promote flexibility and reusability in code by specifying a set of
methods an object can perform, but leaves open how these methods should
be implemented
• can check the class type in runtime
:Features of Java
• High performance
• Java provides native language support

• Slower than compiled language such as C


• an experiment in 1999 showed that Java was 3 or 4 times slower than C or
C++
title of the article: “Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues”
(Lutz Prechelt)
• adequate for all but the most time-intensive programs
Java – compiled and interpreted

•One compilation
•Many interpretations
Java – compiled and interpreted
Java Platform
• The Java platform has two components:
• The Java Virtual Machine (Java VM)
• The Java Application Programming Interface (Java API)
SDK & JRE

•Standard Development Kit


•Java Runtime Enviroment
Important tools
• All tools are in pathtojdk/bin/ directory:
• javac - compiler,
• java - interpreter,
• javadoc – generator of API documentation,
• appletviewer – applet browser,
• jar – tool for jar files
• jdb - debuggger,
First java program: Hello World Application

Write java code

/**

The HelloWorld class implements an application that simply displays “Hello World!” to the standard
output (console)

*/

public class HelloWorld

{

public static void main (String args[])

{

System.out.println(“Hello world!”);

} // end of main …………………………………………..

}// end of class ………………………………………………...

06/28/2023 41
First java program
• 1. Write following code:
• class HelloWorldApp {   
•   public static void main(String[] args) {       
•   System.out.println("Hello World!"); // Display "Hello World!"    
• }}
• 2. Compile it:
• javac HelloWorldApp.java 
• 3. Run the program:
• java HelloWorldApp 
First java program
• Create a Java source file. A source file contains text, written in the Java
programming language, that you and other programmers can understand.

• Compile the source file into a bytecode file. The Java compiler, javac, takes
your source file and translates its text into instructions that the Java Virtual
Machine (Java VM) can understand. The compiler puts these instructions into a
bytecode file.

• Run the program contained in the bytecode file. The Java VM is implemented
by a Java interpreter, java. This interpreter takes your bytecode file and carries
out the instructions by translating them into instructions that your computer can
understand. 
Prototype of the main method

public static void main (String args[])


public is the access specifier.

static is the storage class.

void is the return type.

String args[ ] is an array of arguments.

Check public static void main( ) ? Will it cause any


error? If yes, what?

06/28/2023 44
Using an instance method or variable
;System.out.println(“HelloWorld”)
• System – class
• System.out – full name of variable out. When the System class
is loaded into the application, it instantiates PrintStream and
assigns the new PrintStream object to the out class variable
• PrintStream – type of object out. It has method: println(String);
About main method…

Several main methods can be defined in a java class.

The interpreter will look for a main method with the prescribed
signature as the entry point.

A method named main, which has some other signature is of no particular
significance. It is like any other method in the class.

Therefore, if the main method is not declared correctly, the application will not execute.
There may not be any compilation problem.

This class will compile correctly, but will not execute. The interpreter will say

In class NoMain: void main (String argv[]) is not defined

06/28/2023 46
public class TwoMains Try
{ th i
s…
/** This class has two main methods with * different signatures */
.
public static void main (String args[])
{
//required prototype for main method
System.out.println(“Hello world!”);
int i;
i = main(2);
System.out.println (“i = ” + i );
Outpu
} t will b
e….
/**This is the additional main method*/
public static int main(int i) Hello W
orld!
{ return i*i; } i=4

} // end of class

06/28/2023 47
Defining classes
• Class (template)
• Instanciation – creation of an Object
• Variables
• Methods
Importing classes and packages
• Packages are used to group classes, similar to the way libraries
are used to group C functions.
• Every class is in package
• If the source code for a class doesn't have a package
statement at the top, declaring the package the class is in, then
the class is in the default package.
• Within a package, all classes can refer to each other without
prefixes. For example, the java.awt Component class refers to
the java.awt Graphics class without any prefixes, without
importing the Graphics class.
Comments

There are three types of comments defined by Java.


1. Single-line comment :Java single line comment starts from // and
ends till the end of that line.

2. Multiline comment: Java multiline comment is between /* and */.

3. Documentation comment : Documentation comment is used to produce
an HTML file that documents your program. The documentation comment
begins with a /** and ends with a */.


06/28/2023 50

The end 

06/28/2023 51

You might also like