SlideShare a Scribd company logo
Introduction to
Object-Oriented
Programming
Problem Solving
 The key to designing a solution is breaking it
down into manageable pieces
 When writing software, we design separate
pieces that are responsible for certain parts of
the solution
 Two popular programming design
methods:
 Structured Programming (SP)
 Object-Oriented Programming (OOP)
Problem Solving
SP
 Procedural based approach
 Main problem will be divided into sub-
problems
 Analyze and refine each sub-problem
 All sub-problem solutions are implemented as
procedures and combined to solves the main
problem
Object-Oriented
Programming
 Object based approach
 objects as foundation for problem solving
 Identify objects from the main problem
 An OOP program is a collection of objects
that interacts each other
Object-Oriented
Programming
 More natural way to solve problem
 Objects can be used to represent real-world
entities
 For instance, an object might represent a
particular employee in a company
 Each employee object handles the
processing and data management related to
that employee
Objects
 Object-oriented programs use objects, which
represent real world objects.
 A real world object is a thing, both tangible and
intangible.
 An object has:
 state (it has various properties, which might change)
 behaviour (it can do things and can have things done
to it)
7
Objects
 OOProgramming software objects
 Software objects have state
 Instance Variable/Data/Field
 Software objects have behaviour
 Method
8
Object’s
members
Objects interactions
 OOP also involves interactions between
objects through calling (invoking) of
methods.
9
Method CallsThe OilSensor object calls the warning() method
of the Controller, which then invokes the OilLight
TurnOn() method.
Method can Return Values
 Return value: A result that the method has
computed and returns it to the caller
 Can returns 0 or 1 value
Scanner s = new Scanner(System.in);
int num = s.nextInt();
10
Continued…
Classes and Objects
 To create an object , we MUST provide a
definition/description for it
 A class is a description/blue print of a kind of
object
 It does not by itself create any objects
How to create an object ?
 An object is called an instance of a class
Object instantiation – process of creating an object
11
Example of Java class:
The String Class
12
Creating Objects
 A variable holds either a primitive type or a
reference to an object
 A class name can be used as a type to declare an
object reference variable
String name;
 No object is created with this declaration
 An object reference variable holds the address of
an object
 The object itself must be created separately
13
Creating Objects
 Generally, we use the new operator to create
an object
14
name = new String (“Ali bin Ahmad");
This calls the String constructor, which is
a special method that sets up the object
• Creating an object is called instantiation
• An object is an instance of a particular class
Constructing String
objects
Strings stringRef = new String(stringLiteral);
eg.
String name = new String(“Muhammad Haziq”);
Since strings are used frequently, Java provides a
shorthand notation for creating a string:
String name = "Muhammad Haziq”;
15
Constructing String objects
 New String objects are created whenever the
String constructors are used:
16
String name4 = new String(); // Creates an object
String name5 = new String("Socrates");
String name6 = name4;
Invoking Methods
 We've seen that once an object has been instantiated, we
can use the dot operator to invoke its methods
name.length()
 A method may return a value, which can be used in an
assignment or expression
count = name.length();
S.o.p(“Num. of char in “ + name+ “=“ + count);
 A method invocation can be thought of as asking an object
to perform a service
17
Object without object reference
cannot be accessed
18
String n1 = new String(“Ali“);
new String(“Abu“);
sv1: String
: String
value = “Ali”
value = “Abu”
n1
n1- object reference variable
Object References
 Primitive type variables ≠ object variables
19
References
 Note that a primitive variable contains the value
itself, but an object variable contains the address
of the object
 An object reference can be thought of as a pointer
to the location of the object
 Rather than dealing with arbitrary addresses, we
often depict a reference graphically
20
"Steve Jobs"name1
num1 38
Assignment Revisited
 The act of assignment takes a copy of a value
and stores it in a variable
 For primitive types:
21
num1 38
num2 96
Before:
num2 = num1;
num1 38
num2 38
After:
Object Reference
Assignment
 For object references, assignment copies the
address:
22
name2 = name1;
name1
name2
Before:
"Steve Jobs"
"Steve Austin"
name1
name2
After:
"Steve Jobs"
Questions
23
String stud1 = new String(“Ani”);
int studID = 65000;
What does variable stud1 contains?
What does variable studID contains?
Is this allowed? stud1 = studID;
String stud1;
stud1 = new String(“Ani”);
stud1 = new String(“Obi”);
How many objects were created by the program?
How many reference variables does the program contain?
Writing Classes
 The programs we’ve written in previous
examples have used classes defined in the Java
standard class library
 Now we will begin to design programs that rely
on classes that we write ourselves
 True object-oriented programming is based on
defining classes that represent objects with
well-defined characteristics and functionality
24
Graphical Representation of a
Class
25
The notation we used here is based on the industry standard notation
called UML, which stands for Unified Modeling Language.
A UML Class Diagram
Class Name
Variables
Method
Type of data
Access
Type of
return
value
A class can
contain data
declarations and
method
declarations
Object Instantiation
26
class
object
Object Design Questions
 What role will the object perform?
 What data or information will it need?
 Look for nouns.
 Which actions will it take?
 Look for verbs.
 What interface will it present to other objects?
 These are public methods.
 What information will it hide from other objects?
 These are private.
27
Design Specification for a
Rectangle
 Class Name: Rectangle
 Role: To represent a geometric rectangle
 States (Information or instance variables)
- Length: A variable to store rectangle’s length
(private)
- Width: A variable to store rectangle's width (private)
 Behaviors (public methods)
- Rectangle(): A constructor method to set a rectangle’s
length and width
- calculateArea(): A method to calculate a rectangle’s
area
28
UML Design Specification
29
UML Class Diagram
Class Name
What data does it need?
What behaviors
will it perform?
Public
methods
Hidden
information
Instance variables -- memory locations
used for storing the information needed.
Methods -- blocks of code used to
perform a specific task.
Method can has input (parameter) &
output (return value)
 Parameter : value given to method so that it can
do its task
 Can has 0 or more parameter
 Return value: A result that the method has
computed and returns it to the caller
 Can returns 0 or 1 value
 Eg. - pow(2,3)
- calculateArea()
- getBalance( )
- move( )
30
Continued…
Method Declarations
 A method declaration specifies the code that will
be executed when the method is invoked (called)
 When a method is invoked, the flow of control
jumps to the method and executes its code
 When complete, the flow returns to the place
where the method was called and continues
 The invocation may or may not return a value,
depending on how the method is defined
31
Method Control Flow
 If the called method is in the same class, only
the method name is needed
32
myMethod();
myMethodcompute
Method Control Flow
 The called method is often part of another
class or object
33
doIt helpMe
helpMe();obj.doIt();
main
Method Design
 What specific task will the method perform?
 What input data will it need to perform its
task?
 What result will the method produce?
 How input data are processed into result?
 What algorithm will the method use?
34
Method calculateArea()
Algorithm
 Method Name: calculateArea()
 Task: To calculate the area of a rectangle
 Data Needed (variables)
 length: A variable to store the rectangle's length
 width: A variable to store the rectangle's width
 area: A variable to store result of calculation
 Processing: area = length x width
 Result to be returned: area
35
Coding into Java
36
public class Rectangle // Class header
{
private double length; // Instance variables
private double width;
public Rectangle(double l, double w) // Constructor method
{
length = l;
width = w;
}
public double calculateArea() // calculate area method
{
double area;
area = length * width;
return area;
} // calculateArea()
} // Rectangle class
Method calculatePerimeter()
Algorithm
 Write an algorithm to calculate the perimeter
of a rectangle.
 Write the method in Java.
37
calculatePerimeter()
Algorithm
 Method Name: calculatePerimeter()
 Task: To calculate the perimeter of a
rectangle
 Data Needed (variables)
 length
 width
 perimeter
 Processing: perimeter = 2 x(length + width)
 Result to be returned: perimeter
38
calculatePerimeter() in Java
code
39
public double calculatePerimeter()
{
double perimeter;
perimeter = 2 * (length + width);
return perimeter;
} // calculatePerimeter()
Creating Rectangle Instances
 Create, or instantiate, two instances of the
Rectangle class:
40
The objects (instances)
store actual values.
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25, 20);
Using Rectangle Instances
 We use a method call to ask each object to tell
us its area:
41
rectangle1 area 300
rectangle2 area 500Printed output:
System.out.println("rectangle1 area " + rectangle1.calculateArea());
System.out.println("rectangle2 area " + rectangle2.calculateArea());
References to
objects
Method calls
Syntax : Object Construction
 new ClassName(parameters);
 Example:
 new Rectangle(30, 20);
 new Car("BMW 540ti", 2004);
 Purpose:
 To construct a new object, initialize it with the
construction parameters, and return a
reference to the constructed object.
42
The RectangleUser Class
Definition
public class RectangleUser
{
public static void main(String argv[])
{
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25,20);
System.out.println("rectangle1 area " +
rectangle1.calculateArea());
System.out.println("rectangle2 area " +
rectangle2.calculateArea());
} // main()
} // RectangleUser
43
An application must
have a main() method
Object
Use
Object
Creation
Class
Definition

More Related Content

What's hot

Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
Prof.Nilesh Magar
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Yi-Fan Chu
 
Xml presentation
Xml presentationXml presentation
Xml presentation
Miguel Angel Teheran Garcia
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
Mark Daniel Dacer
 
MatplotLib.pptx
MatplotLib.pptxMatplotLib.pptx
MatplotLib.pptx
Paras Intotech
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
karthikeyanC40
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
Philip Schwarz
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
Edureka!
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
Basant Medhat
 
Review Python
Review PythonReview Python
Review Python
ManishTiwari326
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Data Structure (Stack)
Data Structure (Stack)Data Structure (Stack)
Data Structure (Stack)
Adam Mukharil Bachtiar
 
Data structure tries
Data structure triesData structure tries
Data structure tries
Md. Naim khan
 
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
Nuzhat Memon
 
2 dtd - validating xml documents
2   dtd - validating xml documents2   dtd - validating xml documents
2 dtd - validating xml documents
gauravashq
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
C# program structure
C# program structureC# program structure

What's hot (20)

Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Data structures
Data structuresData structures
Data structures
 
Xml presentation
Xml presentationXml presentation
Xml presentation
 
12 SQL
12 SQL12 SQL
12 SQL
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
MatplotLib.pptx
MatplotLib.pptxMatplotLib.pptx
MatplotLib.pptx
 
Abstract Data Types
Abstract Data TypesAbstract Data Types
Abstract Data Types
 
Tagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also ProgramsTagless Final Encoding - Algebras and Interpreters and also Programs
Tagless Final Encoding - Algebras and Interpreters and also Programs
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
XML and DTD
XML and DTDXML and DTD
XML and DTD
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Review Python
Review PythonReview Python
Review Python
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Data Structure (Stack)
Data Structure (Stack)Data Structure (Stack)
Data Structure (Stack)
 
Data structure tries
Data structure triesData structure tries
Data structure tries
 
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
Std 10 Computer Chapter 3 Handling Images in HTML (Part 1)
 
2 dtd - validating xml documents
2   dtd - validating xml documents2   dtd - validating xml documents
2 dtd - validating xml documents
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
C# program structure
C# program structureC# program structure
C# program structure
 

Viewers also liked

Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationshipsPooja mittal
 
Object and class
Object and classObject and class
Object and class
mohit tripathi
 
Parallel Programming in Python: Speeding up your analysis
Parallel Programming in Python: Speeding up your analysisParallel Programming in Python: Speeding up your analysis
Parallel Programming in Python: Speeding up your analysis
Manojit Nandi
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
rprajat007
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagramSadhana28
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objectsrahulsahay19
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
C++ classes
C++ classesC++ classes
C++ classes
imhammadali
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
Nowell Strite
 

Viewers also liked (10)

Object and class relationships
Object and class relationshipsObject and class relationships
Object and class relationships
 
Object and class
Object and classObject and class
Object and class
 
Parallel Programming in Python: Speeding up your analysis
Parallel Programming in Python: Speeding up your analysisParallel Programming in Python: Speeding up your analysis
Parallel Programming in Python: Speeding up your analysis
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Class and object_diagram
Class  and object_diagramClass  and object_diagram
Class and object_diagram
 
Classes And Objects
Classes And ObjectsClasses And Objects
Classes And Objects
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
class and objects
class and objectsclass and objects
class and objects
 
C++ classes
C++ classesC++ classes
C++ classes
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 

Similar to Class & Object - Intro

00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
MiltonMolla1
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
NuurAxmed2
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
Stefano Fago
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
Abou Bakr Ashraf
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
charancherry185493
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
Hailsh
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
Tareq Hasan
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
Gujarat Technological University
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
John Hunter
 
OOP Principles
OOP PrinciplesOOP Principles
OOP Principles
Upender Upr
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
Mochi263119
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
ITNet
 
34. uml
34. uml34. uml
34. uml
karzansaid
 

Similar to Class & Object - Intro (20)

00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Classes1
Classes1Classes1
Classes1
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
Module 4.pptx
Module 4.pptxModule 4.pptx
Module 4.pptx
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Oop java
Oop javaOop java
Oop java
 
Class and Object.pptx
Class and Object.pptxClass and Object.pptx
Class and Object.pptx
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Java: Objects and Object References
Java: Objects and Object ReferencesJava: Objects and Object References
Java: Objects and Object References
 
Creating classes and applications in java
Creating classes and applications in javaCreating classes and applications in java
Creating classes and applications in java
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
 
OOP Principles
OOP PrinciplesOOP Principles
OOP Principles
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
Core Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class pptCore Java unit no. 1 object and class ppt
Core Java unit no. 1 object and class ppt
 
Ch.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objectsCh.1 oop introduction, classes and objects
Ch.1 oop introduction, classes and objects
 
34. uml
34. uml34. uml
34. uml
 

More from PRN USM

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
PRN USM
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
PRN USM
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
PRN USM
 
Exception Handling
Exception HandlingException Handling
Exception Handling
PRN USM
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
PRN USM
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Array
ArrayArray
Array
PRN USM
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
PRN USM
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
PRN USM
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
PRN USM
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
PRN USM
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
PRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree HomesPRN USM
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean ExperiencePRN USM
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...PRN USM
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesPRN USM
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlPRN USM
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From MhpbPRN USM
 

More from PRN USM (19)

Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2Graphical User Interface (GUI) - 2
Graphical User Interface (GUI) - 2
 
Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1Graphical User Interface (GUI) - 1
Graphical User Interface (GUI) - 1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2Inheritance & Polymorphism - 2
Inheritance & Polymorphism - 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Array
ArrayArray
Array
 
Class & Object - User Defined Method
Class & Object - User Defined MethodClass & Object - User Defined Method
Class & Object - User Defined Method
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
Selection Control Structures
Selection Control StructuresSelection Control Structures
Selection Control Structures
 
Numerical Data And Expression
Numerical Data And ExpressionNumerical Data And Expression
Numerical Data And Expression
 
Introduction To Computer and Java
Introduction To Computer and JavaIntroduction To Computer and Java
Introduction To Computer and Java
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Empowering Women Towards Smokefree Homes
Empowering  Women  Towards  Smokefree  HomesEmpowering  Women  Towards  Smokefree  Homes
Empowering Women Towards Smokefree Homes
 
Sfe The Singaporean Experience
Sfe The Singaporean ExperienceSfe The Singaporean Experience
Sfe The Singaporean Experience
 
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
Corporate Social Responsibility And Challenges In Creating Smoke Free Environ...
 
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And PrioritiesMalaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
Malaysian Health Promotion Board (Mhpb) Objectives, Functions And Priorities
 
Role Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco ControlRole Of Ng Os In Tobacco Control
Role Of Ng Os In Tobacco Control
 
Application Of Grants From Mhpb
Application Of Grants From MhpbApplication Of Grants From Mhpb
Application Of Grants From Mhpb
 

Recently uploaded

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
gb193092
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 

Recently uploaded (20)

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Marketing internship report file for MBA
Marketing internship report file for MBAMarketing internship report file for MBA
Marketing internship report file for MBA
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 

Class & Object - Intro

  • 2. Problem Solving  The key to designing a solution is breaking it down into manageable pieces  When writing software, we design separate pieces that are responsible for certain parts of the solution
  • 3.  Two popular programming design methods:  Structured Programming (SP)  Object-Oriented Programming (OOP) Problem Solving
  • 4. SP  Procedural based approach  Main problem will be divided into sub- problems  Analyze and refine each sub-problem  All sub-problem solutions are implemented as procedures and combined to solves the main problem
  • 5. Object-Oriented Programming  Object based approach  objects as foundation for problem solving  Identify objects from the main problem  An OOP program is a collection of objects that interacts each other
  • 6. Object-Oriented Programming  More natural way to solve problem  Objects can be used to represent real-world entities  For instance, an object might represent a particular employee in a company  Each employee object handles the processing and data management related to that employee
  • 7. Objects  Object-oriented programs use objects, which represent real world objects.  A real world object is a thing, both tangible and intangible.  An object has:  state (it has various properties, which might change)  behaviour (it can do things and can have things done to it) 7
  • 8. Objects  OOProgramming software objects  Software objects have state  Instance Variable/Data/Field  Software objects have behaviour  Method 8 Object’s members
  • 9. Objects interactions  OOP also involves interactions between objects through calling (invoking) of methods. 9 Method CallsThe OilSensor object calls the warning() method of the Controller, which then invokes the OilLight TurnOn() method.
  • 10. Method can Return Values  Return value: A result that the method has computed and returns it to the caller  Can returns 0 or 1 value Scanner s = new Scanner(System.in); int num = s.nextInt(); 10 Continued…
  • 11. Classes and Objects  To create an object , we MUST provide a definition/description for it  A class is a description/blue print of a kind of object  It does not by itself create any objects How to create an object ?  An object is called an instance of a class Object instantiation – process of creating an object 11
  • 12. Example of Java class: The String Class 12
  • 13. Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference variable String name;  No object is created with this declaration  An object reference variable holds the address of an object  The object itself must be created separately 13
  • 14. Creating Objects  Generally, we use the new operator to create an object 14 name = new String (“Ali bin Ahmad"); This calls the String constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class
  • 15. Constructing String objects Strings stringRef = new String(stringLiteral); eg. String name = new String(“Muhammad Haziq”); Since strings are used frequently, Java provides a shorthand notation for creating a string: String name = "Muhammad Haziq”; 15
  • 16. Constructing String objects  New String objects are created whenever the String constructors are used: 16 String name4 = new String(); // Creates an object String name5 = new String("Socrates"); String name6 = name4;
  • 17. Invoking Methods  We've seen that once an object has been instantiated, we can use the dot operator to invoke its methods name.length()  A method may return a value, which can be used in an assignment or expression count = name.length(); S.o.p(“Num. of char in “ + name+ “=“ + count);  A method invocation can be thought of as asking an object to perform a service 17
  • 18. Object without object reference cannot be accessed 18 String n1 = new String(“Ali“); new String(“Abu“); sv1: String : String value = “Ali” value = “Abu” n1 n1- object reference variable
  • 19. Object References  Primitive type variables ≠ object variables 19
  • 20. References  Note that a primitive variable contains the value itself, but an object variable contains the address of the object  An object reference can be thought of as a pointer to the location of the object  Rather than dealing with arbitrary addresses, we often depict a reference graphically 20 "Steve Jobs"name1 num1 38
  • 21. Assignment Revisited  The act of assignment takes a copy of a value and stores it in a variable  For primitive types: 21 num1 38 num2 96 Before: num2 = num1; num1 38 num2 38 After:
  • 22. Object Reference Assignment  For object references, assignment copies the address: 22 name2 = name1; name1 name2 Before: "Steve Jobs" "Steve Austin" name1 name2 After: "Steve Jobs"
  • 23. Questions 23 String stud1 = new String(“Ani”); int studID = 65000; What does variable stud1 contains? What does variable studID contains? Is this allowed? stud1 = studID; String stud1; stud1 = new String(“Ani”); stud1 = new String(“Obi”); How many objects were created by the program? How many reference variables does the program contain?
  • 24. Writing Classes  The programs we’ve written in previous examples have used classes defined in the Java standard class library  Now we will begin to design programs that rely on classes that we write ourselves  True object-oriented programming is based on defining classes that represent objects with well-defined characteristics and functionality 24
  • 25. Graphical Representation of a Class 25 The notation we used here is based on the industry standard notation called UML, which stands for Unified Modeling Language. A UML Class Diagram Class Name Variables Method Type of data Access Type of return value A class can contain data declarations and method declarations
  • 27. Object Design Questions  What role will the object perform?  What data or information will it need?  Look for nouns.  Which actions will it take?  Look for verbs.  What interface will it present to other objects?  These are public methods.  What information will it hide from other objects?  These are private. 27
  • 28. Design Specification for a Rectangle  Class Name: Rectangle  Role: To represent a geometric rectangle  States (Information or instance variables) - Length: A variable to store rectangle’s length (private) - Width: A variable to store rectangle's width (private)  Behaviors (public methods) - Rectangle(): A constructor method to set a rectangle’s length and width - calculateArea(): A method to calculate a rectangle’s area 28
  • 29. UML Design Specification 29 UML Class Diagram Class Name What data does it need? What behaviors will it perform? Public methods Hidden information Instance variables -- memory locations used for storing the information needed. Methods -- blocks of code used to perform a specific task.
  • 30. Method can has input (parameter) & output (return value)  Parameter : value given to method so that it can do its task  Can has 0 or more parameter  Return value: A result that the method has computed and returns it to the caller  Can returns 0 or 1 value  Eg. - pow(2,3) - calculateArea() - getBalance( ) - move( ) 30 Continued…
  • 31. Method Declarations  A method declaration specifies the code that will be executed when the method is invoked (called)  When a method is invoked, the flow of control jumps to the method and executes its code  When complete, the flow returns to the place where the method was called and continues  The invocation may or may not return a value, depending on how the method is defined 31
  • 32. Method Control Flow  If the called method is in the same class, only the method name is needed 32 myMethod(); myMethodcompute
  • 33. Method Control Flow  The called method is often part of another class or object 33 doIt helpMe helpMe();obj.doIt(); main
  • 34. Method Design  What specific task will the method perform?  What input data will it need to perform its task?  What result will the method produce?  How input data are processed into result?  What algorithm will the method use? 34
  • 35. Method calculateArea() Algorithm  Method Name: calculateArea()  Task: To calculate the area of a rectangle  Data Needed (variables)  length: A variable to store the rectangle's length  width: A variable to store the rectangle's width  area: A variable to store result of calculation  Processing: area = length x width  Result to be returned: area 35
  • 36. Coding into Java 36 public class Rectangle // Class header { private double length; // Instance variables private double width; public Rectangle(double l, double w) // Constructor method { length = l; width = w; } public double calculateArea() // calculate area method { double area; area = length * width; return area; } // calculateArea() } // Rectangle class
  • 37. Method calculatePerimeter() Algorithm  Write an algorithm to calculate the perimeter of a rectangle.  Write the method in Java. 37
  • 38. calculatePerimeter() Algorithm  Method Name: calculatePerimeter()  Task: To calculate the perimeter of a rectangle  Data Needed (variables)  length  width  perimeter  Processing: perimeter = 2 x(length + width)  Result to be returned: perimeter 38
  • 39. calculatePerimeter() in Java code 39 public double calculatePerimeter() { double perimeter; perimeter = 2 * (length + width); return perimeter; } // calculatePerimeter()
  • 40. Creating Rectangle Instances  Create, or instantiate, two instances of the Rectangle class: 40 The objects (instances) store actual values. Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25, 20);
  • 41. Using Rectangle Instances  We use a method call to ask each object to tell us its area: 41 rectangle1 area 300 rectangle2 area 500Printed output: System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); References to objects Method calls
  • 42. Syntax : Object Construction  new ClassName(parameters);  Example:  new Rectangle(30, 20);  new Car("BMW 540ti", 2004);  Purpose:  To construct a new object, initialize it with the construction parameters, and return a reference to the constructed object. 42
  • 43. The RectangleUser Class Definition public class RectangleUser { public static void main(String argv[]) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // main() } // RectangleUser 43 An application must have a main() method Object Use Object Creation Class Definition