Chapter 1 (Oop)
Chapter 1 (Oop)
Chapter 1 (Oop)
Introduction to Ob-
ject Oriented Pro-
gramming
1
PROCEDURAL VS OBJECT ORIENTED PROGRAM-
MING
objects
4
WHY DO WE NEED OBJECT-ORIENTED
PROGRAMMING?
A procedural program is divided into functions, and
(ideally, at least) each function has a clearly defined
purpose and a clearly defined interface to the other
functions in the program
In a large program, there are many functions and many
5
CONT’D
This large number of connections causes problems in sev-
eral ways
it makes a program’s structure difficult to conceptualize,
modify
•When data items are modified in a large program it may
not be easy to tell which functions access the data, and
even when you figure this out, modifications to the func-
tions may cause them to work incorrectly with other global
data items
its arrangement of separate data and functions does a
7
CONT’D
The unit in procedural programming is function, and unit
in object-oriented programming is class
Procedural programming concentrates on creating func-
that data 11
CONT’D
An object
is an instance of a class
invocation of a method.
You can create many instances of a class. Creating an in-
12
CONT’D
Difference Between Classes and Objects
Example
a Car Class which can be used to define several Car
Objects.
Car A and Car B are objects of the Car class.
Brake.
13
CONT’D
14
Compare the state and behavior of a television to the states and behaviors of a car.
CONT’D
15
CONT’D
Members
The code and data that constitute a class are called members
of the class.
The data defined by the class are referred to as member vari-
16
CLASS MEMBER VISIBILITY
17
BASIC CONCEPT OF UML
CLASS INFORMATION: VISIBILITY AND SCOPE
The class notation is a 3-piece rectangle with the class name, attributes, and operations. Attributes and operations can
be labeled according to access and scope. Here is a new, expanded Order class.
The class notation is a 3-piece rectangle with the class name, attributes, and operations. At-
tributes and operations can be labeled according to access and scope. Here is a new, ex-
panded Order class.
Symbol Access
+ public 18
- private
# protected
SUMMARY OF OBJECT-ORIENTED CON-
CEPTS
Everything is an object.
Computation is performed by objects communicating with
19
CONT’D
Each object has its own memory, which consists of other objects.
Every object is an instance of a class.
A class simply represents a grouping of similar objects, such as Inte-
gers or lists.
The class is the repository for behavior associated with an object.
That is, that all objects that are instances of the same class can per-
form the same actions.
Java programmers concentrate on creating their own user-defined
types, called classes.
Each class contains data and the set of functions that manipulate
that data.
The data components of a Java class are called attributes.
The function components of a Java class are called methods.
20
Introduction to Java programming
Java
write once, run anywhere
is a platform independent programming language
similar to C++ in syntax
pros: also ubiquitous /omnipresent to net
Cons: interpreted, and still under development(moving target)
Features of java program
Automatic type checking
Simplifies pointers: no directly accessible pointer to memory
Simplified network access
Multi-threading
Automatic garbage collection
Java performs automatic garbage collection of memory to help return memory
back to the system.
When an object is no longer used in the program (i.e., there are no references
to the object), the object is marked for garbage collection.
The memory for such an object can be reclaimed when the garbage collector
21
executes.
CONT’D
Java is independent only for one reason
Only depends on the Java Virtual Machine(JVM)
Code is compiled to bytecode, which is interpreted by the resident
JVM
JIT(just in time) compilers attempt to increase speed
An intermediate step between interpreters and compilers is a just-in-
time (JIT) compiler that, as the interpreter runs, produces compiled
code for the programs and executes the programs in machine language
rather than reinterpreting them.
JIT compilers do not produce machine language that is as efficient as a
full compiler
Portable- write once, run anywhere
Security has been well thought through
Robust memory management
making your program fault tolerant (handling errors).
22
CONT’D
Dynamic and extensible(loads of libraries)
Classes stored in separate files
Loaded only when needed
A bytecode is a special machine language that can be under-
stood by the Java Virtual Machine (JVM).
The bytecode is independent of any particular computer
structions
24
JAVA API PACKAGES
Java contains many predefined classes that are grouped into
categories of related classes called packages.
The packages are referred to collectively as the Java class li-
brary or the Java applications programming interface (Java
API) or the Java class library.
import statements specify the classes required to compile a
Java program
One of the great strengths of Java is the large number of
classes in the packages of the Java API that programmers can
reuse rather than “reinventing the wheel.”
Example
import javax.swing.JApplet;
to tell the compiler to load the JApplet class from the
javax.swing package
25
CONT’D
Java programs consist of pieces called classes.
Classes consist of pieces called methods that perform tasks and
return information when they complete their tasks.
You can program each piece you may need to form a Java pro-
gram.
However, most Java programmers take advantage of rich collec-
tions of existing classes in Java class libraries.
The class libraries are also known as the Java APIs.
Thus, there are really two pieces to learning the Java “world.”
The first is learning the Java language itself so that you can program
your own classes;
the second is learning how to use the classes in the extensive Java
class libraries.
Ex. Math.pow(x, y) calculates the value of x raised to the y th
power
26
PHASES OF A JAVA PROGRAM
27
CONT’D
28
CONT’D
Editor – To type your program into , a editor could be
used for this
Compiler – To convert your high language program into
native machine code - bytecodes
Loader – To load the files from your secondary storage
device like Hard Disk , Flash Drive , CD into RAM for exe-
cution. The loading is automatically done when your code
execute your code.
Bytecode Verifier- To ensure that the bytecodes for
downloaded classes are valid and that they do not violate
Java’s security restrictions.
Interpreter – To interpret the program one bytecode at a
time, 29
thus performing the actions specified by the program
CONT’D
30
SIMPLE JAVA PROGRAM
Step 1 ) Copy the following code into a notepad.
class A {
public static void main(String args[])
{
System.out.println(“First Java Program”);
}
}
sion.
Filenames should match the name of your public class. So for
33
CONT’D…
Writing my second example
let’s look at a simple problem for computing the area of a circle. How
do we write a program for solving this problem?
public class ComputeArea
{
public static void main(String[] args)
{
// The main method is the entry point where the program starts when it is exe-
cuted
double radius; // Declare radius
double area; // Declare area
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;
System.out.println("The area for the circle of radius " +
radius + " is " + area); 34
}
}
CONT’D
Class
It is keyword which is used to declare a class
Public:
It is called access modifier or spacifier
It is used to define accessibility of data members (variable and member func-
tion(methods)).
Static
Used for memory management
Can be used is variable function and block.
Static members are belongs to class rather than object(can be called directly by
the class name).
Static variable function and block will be in the following section.
Void:
there is no value to be returned by the function.
Main():
The execution of any program starts from the main function.
String[] args:
It is command line argument that you can write anything in place of args.
System.out: stands output object
Print: is a method or function 35
JAVA PROGRAM PRIMITIVES/ BASICS
Java Comments
Java Statements and blocks
Java Identifiers
Java Keywords
Variables
System.out.println() vs. System.out.print()
Reference Variables vs. Primitive Variables
Primitive variables
are variables with primitive data types. They store data in the actual
memory location of where the variable is.
Reference variables
are variables that stores the address in the memory location.
It points to another memory location of where the actual data
is
When you declare a variable of a certain class, you are actually
declaring a reference variable to the object with that certain36
class.
JAVA COMMENT
It is additional expression about which you are doing.
Two kinds of comment
Single line comment (//)
Multiline comment
/*
---
------
-----
*/
Java statement and block
{
double radius;
double area;
radius = 20;
37
}
IDENTIFIERS
the names of things that appear in the program..
All identifiers must obey the following rules:
An identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar signs ($).
An identifier must start with a letter, an underscore (_), or a dollar sign
($).
It cannot start with a digit.
An identifier cannot be a reserved word.
An identifier cannot be true, false, or null.
An identifier can be of any length. 38
JAVA KEYWORD
The word which is pre-defined in the library
Its functionality also pre-defined.
class name.
Examples:
int
float
char
void
main
39
VARIABLES
variables are used to store values to be used later in a pro-
gram.
They are called variables because their values can be
changed.
In the program radius and area are variables of double-preci-
sion.
Variables are for representing data of a certain type.
To use a variable, you declare it by telling the compiler its
name as well as what type of data it can store.
The variable declaration tells the compiler to allocate appro-
priate memory space for the variable based on its data type.
The syntax for declaring a variable is
datatype variable Name;
40
SYSTEM.OUT.PRINTLN()
VS.
SYSTEM.OUT.PRINT()
System.out.print()
Print the output with the same line
42
CONT’D
Operators
Arithmetic operators
Relational operators
Logical operators
Operator Precedence
43
OPERATORS
Java Arithmetic and Increment/Decrement operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, division Modulus, Increment, Decrement.
They act as basic mathematical operations.
{
int a=10;
int b=5;
System.out.println(++a+b);//16
}
Java Assignment Operators
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
{
int b=5;
} 44
OPERATORS…
int x = 5;
int y = 3;
System.out.println(x == y);
} 45
OPERATORS…
Java Logical Operators
Logical operators are used to determine the logic between
variables or values:
Logical and(&&), logical or(||) and logical not(!)
{
int x = 5;
System.out.println(x > 3 || x < 4);
/* returns true because one of the conditions
are true (5 is greater than 3, but 5 is not less
than 4)
*/
}
46
OPERATORS…
Conditional Operator (?:)
The Java Conditional Operator selects one of two expressions for
evaluation, which is based on the value of the first operands.
It is also called ternary operator because it takes three arguments.
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
// Value of y is:90
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
// Value of y is:90
}
Operator Precedence
*, /, %, (+ or – from left to right).
47
OPERATORS…
Getting Input from the Keyboard
Java Scanner class allows the user to take input from the
console.
It belongs to java.util package.
It is used to read the input of primitive types like int, double,
long, short, float, and byte.
It is the easiest way to read input in Java program.
The java.util package should be import while using Scanner
class.
Syntax
Scanner sc=new Scanner(System.in);
Methods of Java Scanner Class
Java Scanner class provides the following methods to read dif-
48
ferent primitives types:
OPERATORS…
Method Description
Branching Statements
break statement
continue statement
return statement
51
.
CONTROL STRUCTURES/IF/
Use the if statement to specify a bloc of Java code to
be executed if a condition is true
Syntax:
if (condition)
{ // block of code to be executed if the condition is
true
}
Example:
if (20 > 18)
{
System.out.println("20 is greater than 18");
}
Self test
Write a java program that will display “young” if your age is
52
less than 20.
}
SE), Java Enterprise Edition (Java EE), and Java Micro Edi-
tion (Java ME).
59
CONT’D
Java SE can be used to develop client-side standalone applica-
tions or applets.
Java EE can be used to develop server-side applications, such
as Java servlets and JavaServer Pages.
Java ME can be used to develop applications for mobile de-
vices, such as cell phones.
There are many versions of Java SE -JDK
JDK consists of a set of separate programs, each invoked from
a command line, for developing and testing Java programs.
Besides JDK, you can use a Java development tool (e.g., Net-
Beans, Eclipse, and TextPad)—software that provides an inte-
grated development environment (IDE) for rapidly developing
Java programs. 60
EXERCISES
Write a Java application that calculates and prints the sum of the inte-
gers from 10 to 50
Write a program that inputs five numbers and determines and prints
the number of negative numbers input, the number of positive num-
bers input and the number of zeros input.
Write a Java application that uses looping to print the following table
of values:
Write a Java application that can compute the letter grade of a stu-
dent after accepting the student’s mid and final mark. The program
should only accept mid result [0-40] and final [0- 60]. If the data en-
tered violates this rule, the program should display that the user
should enter the mark in the specified range. The program is also ex-
pected to run until the user refuses to continue. 61
CONT’D
Write an application that prints the following diamond
shape.
62