Chapter 1 (Oop)

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 62

CHAPTER ONE

Introduction to Ob-
ject Oriented Pro-
gramming
1
PROCEDURAL VS OBJECT ORIENTED PROGRAM-
MING

• procedural programming languages are made up of modules,


which are parts of a program that can be coded and tested
separately.
• These modules are a procedure that has a sequence of state-
ments.
• The design method used in procedural programming is called
Top-Down design.
• This is where you start with a problem (procedure) and then
systematically break the problem down into sub problems (sub
procedures).
• This is called functional decomposition, which continues until a
sub problem is straightforward enough to be solved by the
corresponding sub procedure.
2
CONT’D
• Procedural programming separates the data of the program
from the operations that manipulate the data.
• The difficulties with this type of programming is that
– Software maintenance can be difficult and time consuming.
– When changes are made to the main procedure (top), those
changes can cascade (flow) to the sub procedures of main, and the
sub-sub procedures and so on, where the change may impact all
procedures in the pyramid.
• One alternative to procedural programming is object oriented
programming.
• Object oriented programming is meant (intended/proposed)
to address the difficulties with procedural programming.
3
OBJECT ORIENTED PROGRAM-
MING
 In object oriented programming, the main part in a program
are classes, rather than procedures.
 The object-oriented approach lets (allows) you create classes

and objects that model real world objects.


Example: Student
 Decomposition of a problem into a number of entities called

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

global data items.


 The problem with the procedural paradigm is that this

leads to an even larger number of potential connections


between functions and data

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

poor job of modeling things in the real world


•Complex real-world objects have both attributes and be-
havior 6
POP VS OOP

7
CONT’D
 The unit in procedural programming is function, and unit
in object-oriented programming is class
 Procedural programming concentrates on creating func-

tions, while object-oriented programming starts from


isolating the classes, and then look for the methods in-
side them.
 Procedural programming separates the data of the pro-

gram from the operations that manipulate the data,


while object-oriented programming focus on both of
them
 OOP is a programming methodology that helps organize

complex programs through the use of inheritance, en-


capsulation, and polymorphism 8
BASIC CHARACTERISTICS OF OBJECT
ORIENTED PROGRAMMING
 Modularity: The source code for a class can be

written and maintained independently of the


source code for other classes. Once created, an
object can be easily passed around inside the
system.
 Information-hiding: By interacting only with an

object's methods, the details of its internal im-


plementation remain hidden from the outside
world.
 Method abstraction is achieved by separating the use of
a method from its implementation. The client can use a 9
method without knowing how it is implemented.
CONT’D
 The details of the implementation are encapsulated in
the method and hidden from the client who invokes the
method. This is known as information hiding or encap-
sulation.
 Code re-use: If a class already exists, you can use objects
from that class in your program. This allows program-
mers to implement/test/debug complex, task-specific
objects, which you can then use in your own code.
 Easy Debugging: If a particular object turns out to be a
problem, you can simply remove it from your applica-
tion and plug in a different object as its replacement.
 This is analogous to fixing mechanical problems in the
real world. If a bolt breaks, you replace it, not the entire
machine.
10
BASIC CONCEPTS OF OBJECT ORI-
ENTED PROGRAMMING
A class is
 Collection of objects that have common properties,
operations and behaviors.
 Combination of state (data) and behavior
(methods).
 In object-oriented languages, a class is a data type,

and objects are instances of that data type.


 Prototypes from which objects are created.
 is a template for holding an object
 It specifies both the data and the code that will operate on

that data 11
CONT’D
An object
 is an instance of a class

 can communicate with other objects using messages.

 passes a message to another object, which results in the

invocation of a method.
 You can create many instances of a class. Creating an in-

stance is referred to as instantiation

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.

 The class has fields plate number, color, manufac-

turer, and current speed which are filled-up with cor-


responding values in objects Car A and Car B.
 The Car has also some methods Accelerate, Turn and

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-

ables or instance variables.


 The code that operates on that data is referred to as member

methods or just methods.


 Fields and methods are referred to as class members.

16
CLASS MEMBER VISIBILITY

 Determine the visibilities of an object’s attributes and


methods to other objects.
 private: private members are accessible only in the
class itself
 protected: protected members are accessible in
classes in the same package, in subclasses of the
class, and in the class itself
 public: public members are accessible anywhere the
class is accessible

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

each other, requesting that other objects perform actions.


 Objects communicate by sending and receiving messages.

 A message is a request for action, bundled with whatever ar-

guments may be necessary to complete the tasks.

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

hardware, so any computer with a Java interpreter can execute


the compiled Java program, no matter what type of computer
the program was compiled on.
 The JVM provides the hardware platform specifications to

which you compile all Java technology code


23
The JVM and Byte Code
 The Java language is a high-level language while Java
bytecode is a low-level language.
 The bytecode is similar to machine instructions but its

architecture is neutral and can run on any platform that


has a Java Virtual Machine (JVM)
 Rather than a physical machine, the virtual machine is a

program that interprets Java bytecode.


 This is one of Java’s primary advanatages: Java bytecode

can run on a variety of hardware platforms and operat-


ing systems.
 Java’s bytecodes are portable- platform-independent in-

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”);
}
}

Step 2 ) Save the file in the directory C:workspace , as A.java

Step 3 ) Open the command prompt Go to Directory C:workspace


Compile the code using command, javac A.java
Step 4) Run the code using command, java A
31
CONT’D
 When you execute the Java Virtual Machine (JVM) with the
java command, the JVM attempts to invoke the main method
of the class you specify.
 The JVM loads the class specified by Class Name and uses
that class name to invoke method main.
 You can specify an optional list of Strings (separated by spa-
ces) as command-line arguments that the JVM will pass to
your application.
 Why must main be declared static?
 When you execute the Java Virtual Machine (JVM) with the java
command, the JVM attempts to invoke the main method of the
class you specify—when no objects of the class have been created.
 Declaring main as static allows the JVM to invoke main with-
out creating an instance of the class.
32
CONT’D
Coding Guidelines:
 Your Java programs should always end with the .java exten-

sion.
 Filenames should match the name of your public class. So for

example, if the name of your public class is Hello, you should


save it in a file called Hello.java.
 You should write comments in your code explaining what a

certain class does, or what a certain method do.

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.

 Keywords can not be used as a variable, function, and

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

System.out.print("hellow world ");


System.out.print(“this is my first java program");
 System.out.println()
 Print the output with different line.
System.out.println("hellow world ");
System.out.println(“this is my first java program");
41
 Data Types in Java
 Data types specify the different sizes and values that can be
stored in the variable. There are two types of data types in
Java:
 Primitive data types: The primitive data types include bool-
ean, char, byte, short, int, long, float and double.
 Non-primitive data types: The non-primitive data types in-
clude
 Classes
 Interfaces
 Arrays

42
CONT’D
 Operators
 Arithmetic operators

 Increment and Decrement operators

 Relational operators

 Logical operators

 Conditional Operator (?:)

 Operator Precedence

 Getting Input from the Keyboard

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…

 Java Comparison Operators


 Comparison operators are used to compare two values:

 (<, >, ==, !=, <=, >= )

int x = 5;

int y = 3;

System.out.println(x == y);

// returns false because 5 is not equal to 3

} 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

int nextInt() It is used to scan the next to-


ken of the input as an integer.

float nextFloat() It is used to scan the next to-


ken of the input as a float.

double nextDouble() It is used to scan the next to-


ken of the input as a double.

byte nextByte() It is used to scan the next to-


ken of the input as a byte.

String nextLine() Advances this scanner past the 49


current line.
OPERATORS…
import java.util.*;
class UserInputDemo
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
//System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
} 50
}
CONT’D
 Control Structures
 Decision Control Structures

 Repetition Control Structures

 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.
}

CONTROL STRUCTURES/IF ELSE/


 Use the else statement to specify a block of code to be
executed if the condition is false.
 Syntax:
if (condition)
{
// block of code to be executed if the condition is
true
}
Else
{
// block of code to be executed if the condition is
false
 Example
int time = 20;
if (time < 18)
{
System.out.println("Good day."); 53
} else {
System.out.println("Good evening.");
CONTROL STRUCTURES/ELSE IF/
 Use the else if statement to specify a new condition if
the first condition is false and so on.
 Syntax:
if (condition1)
{ // block of code to be executed if condition1 is true
}
else if (condition2)
{
executed if the condition1 is false and condition2 is true
}
else {
// executed if the condition1 is false and condition2 is
false
}
Example:
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
} else if (time < 20)
{
System.out.println("Good day.");
} 54
else {
System.out.println("Good evening.");
}
CONTROL STRUCTURES/SWITCH/
 Use the switch statement to select one of many
code blocks to be executed.
 The switch expression is evaluated once.
 The value of the expression is compared with the values
of each case.
 If there is a match, the associated block of code is exe-
cuted.
 Syntax:
switch(expression)
{
case x: // code block
break;
case y: // code block
break;
55
default: // code block }
CONT’D
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
default:
56
System.out.println("Sunday");
}
REPETITION CONTROL
STRUCTURES/WHILE LOOP/
 Loops can execute a block of code as long as a specified condition is
reached.
 Loops are handy because they save time, reduce errors, and they make
code more readable.
 The while loop loops through a block of code as long as a
specified condition is true:

Syntax
while (condition)
{ // code block to be executed
}
 Example:
int i = 0;
while (i < 5)
{
System.out.println(i);
i++; 57
}
REPETITION CONTROL STRUCTURES/
FOR LOOP/
 When you know exactly how many times you want to
loop through a block of code, use the for loop instead
of a while loop
 Syntax
for (statement 1; statement 2; statement3)
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of
the code block.
Statement 2 defines the condition for executing the code
block.
Statement 3 is executed (every time) after the code block
has been executed.
 Example:
for (int i = 0; i < 5; i++)
{ System.out.println(i); 58
}
JAVA APPLICATION
 Is a computer program that executes when you use the
java command to launch the Java Virtual Machine (JVM)
 The application program interface (API) contains prede-

fined classes and interfaces for developing Java pro-


grams.
 Java is a full-fledged and powerful language that can be

used in many ways.


 Java comes in three editions: Java Standard Edition (Java

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy