SlideShare a Scribd company logo
Discovering Knowledge
CS-205 Object-Oriented
Programming
1
Discovering Knowledge
Gentle Reminder
“Switch Off” your Mobile Phone Or Switch
Mobile Phone to “Silent Mode”
2
Discovering Knowledge
Fundamentals of Object Oriented
Programming
3
Discovering Knowledge
OOP PARADIGM
• Emphasis on objects (what objects are needed in this
program?) rather than procedure (what does this program
need to do?).
• Programs are divided into entities known as classes of objects.
• Data Structures are designed such that they characterize
objects.
• Functions that operate on data of an object are tied together
in data structures.
• Data is hidden and cannot be accessed by external functions.
• Objects communicate with each other through functions.
• New data and functions can be easily added whenever
necessary.
• Follows bottom up approach in program design.
4
Discovering Knowledge
Organization of Data and Functions in
OOP
Data
Member
Function
Member
Function
©
Discovering Knowledge
Basic Concepts in OOP
• Objects
• Classes
• Message Passing
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
• Dynamic Binding
6
Discovering Knowledge
Objects
• Objects are the basic run-time entities of an object
oriented system.
• They may represent a person, a place or any item
that the program must handle.
• Example
Representation of an object
7
Discovering Knowledge
Objects
Objects are made up of two "things":
• State (a.k.a. attributes/fields/properties + value)
- A given set of data which describes the object
- e.g., colour,size,amount,name,phoneNumber,etc...
• Behaviour (a.k.a. methods or functions)
- A set of operations that the object can perform
- e.g., walk, run, drive, sell, buy, transfer, computeTotal, open,
close, etc…
Identifying the state and behavior for real-world objects is a great
way to begin thinking in terms of object-oriented programming.
8
Discovering Knowledge
Example of Object,State,Behaviour
9
Discovering Knowledge
Classes
• A class defines the type of an object.
• A class is a prototype/template or a blue print of an object.
• A class is a specification, common to all objects of a
particular type.
• This specification contains the details of the data and
functions that act upon the data.(data+functions)
• Objects of a class are called individual instances of that
class.
• Any number of objects can be created based on a class.
10
Discovering Knowledge
Classes
• We can create object of a class using following
syntax,
• Syntax: ClassName objectName;
• Here ClassName is a class which is already defined
and objectName is any user-defined name.
• For example, if Student is a class,
Student shahid, kamran;
In the example, shahid and kamran are the names of the
objects of class Student. We can declare/create any number of
objects of a class.
11
Discovering Knowledge
Classes
• Diagram showing the relationship between Classes and Objects
• Other examples of classes are: Instructor, Student, Room, University,
Car, etc.
go to slide Number 28 12
Discovering Knowledge
Message Passing
• A message for an object is a request for execution of a
procedure and therefore will invoke a function in the
receiving object that generates the desired result.
• Message passing involves specifying the name of the
object, the name of the function i.e. message and the
information to be sent.
• Objects can communicate with each other by passing
messages same as people pass messages to each other.
• Objects can send or receive messages or information.
• Concept of message passing makes it easier to talk
about building systems that directly model or simulate
their real-world counterparts.
13
Discovering Knowledge
Message Passing
• For example, consider two classes Product and
Order. The object of the Product class can
communicate with the object of the Order
class by sending a request for placing order.
14
Discovering Knowledge
Abstraction
• Abstraction refers to the representation of necessary
features without including details or explanations.
• Classes use the concept of abstraction and are defined
as a list of abstract attributes and functions to operate
on these attributes.
• Data abstraction is a programming (and design)
technique that relies on the separation of interface and
implementation.
- Implementation denotes how variables are declared, how
functions are coded, etc. It is through interface (function
header/function signature) a communication is sent to the
object as messages.
15
Discovering Knowledge
Abstraction
• When you press a key on your
keyboard the character appears on
the screen, you need to know only
this, but How exactly it works
electronically, is not needed.
• Another Example is when you use the
remote control of your TV, you do not
bother about how pressing a key in
the remote changes the channel on
the TV. You just know that pressing
the + volume button will increase the
volume.
16
Discovering Knowledge
Encapsulation
• Encapsulation is the principle of object-oriented
programming.
• In simple words, “Encapsulation is a process of
binding data members (variables, properties) and
member functions (methods) into a single unit”.
17
Discovering Knowledge
Encapsulation
• The data is not accessible to the outside world, and
only those functions which are wrapped in the class
can access it.
• These functions provide the interface between the
objects data and the program. This insulation of the
data from direct access by the program is called data
hiding or information hiding.
• A Class is the best example of encapsulation.
18
Discovering Knowledge
Encapsulation
For example: Medical store
• Lets say you have to buy some medicines. You go to the
medical store and ask the chemist for the medicines.
• Only the chemist has access to the medicines in the store
based on your prescription.
• The chemist knows what medicines to give to you.
• This reduces the risk of you taking any medicine that is not
intended for you.
In this example,
• Medicines Æ Member Variables.
• Giving Medicine by Chemist Æ Member Methods.
• You Æ External Application or piece of Code.
19
Discovering Knowledge
Difference between Abstraction and
Encapsulation
S# Abstraction Encapsulation
1 Abstraction solves the problem in Encapsulation solves the problem in the
the design level. implementation level.
2 Abstraction is used for hiding the Encapsulation means hiding the code and
unwanted data and giving relevant data into a single unit to protect the data
data. from outside world.
3 Abstraction lets you focus on what Encapsulation means hiding the internal
the object does instead of how it details or mechanics of how an object
does it. does something.
4 Abstraction- Outer layout, used in
terms of design.
For Example:-
Outer Look of a Mobile Phone, like
it has a display screen and keypad
buttons to dial a number.
Encapsulation- Inner layout, used in terms
of implementation.
For Example:- Inner Implementation
details of a Mobile Phone, how keypad
button and Display Screen are connected
with each other using circuits.
20
Discovering Knowledge
Inheritance
• Inheritance is the process by which
object of one class acquire the
properties of objects of another
class.
• In OOP, the concept of inheritance
provides the idea of reusability.
This means that we can add
additional features to an existing
class without modifying it.
• This is possible by deriving a new
class from the existing one. The
new class will have combined
features of both the classes.
21
Discovering Knowledge
Inheritance
• For Example:
• Consider an example of family of three
members having a mother, father & son named
Jack.
• Jack father : tall and dark
• Jack mother: Short and fair
• Jack is tall and fair,so he is said to have
inherited the features of his father and mother
respectively.
22
Discovering Knowledge
Inheritance
• Through effective use of inheritance, you can
save a lot of time in your programming and
also reduce error.
• Which in turn will increase the quality of work
and productivity.
• We will explain all of the above in detail later
when we cover Inheritance.
23
Discovering Knowledge
Polymorphism
• Polymorphism is an important OOP concept.
• Polymorphism is a Greek term which means
the ability to take more than one form.
• In polymorphism an operation may show
different behavior in different instances.
Poly Morphism Polymorphism
(Many) (Forms) (Many Forms)
24
Discovering Knowledge
Polymorphism
• For example, + is used to make sum of two numbers
as well as it is used to combine two strings.
• This is known as operator overloading because same
operator may behave differently on different
instances.
25
Discovering Knowledge
Polymorphism
• Same way functions can be overloaded.
• For example, sum()function may take two
arguments or three arguments etc.
- i.e. sum (5, 7) or sum (4, 6, 8).
• Single function Draw() draws different objects.
26
Discovering Knowledge
Dynamic Binding
• Dynamic Binding is the process of linking of
the code associated with a procedure call at
the run-time”.
• Dynamic binding means that the code
associated with a given procedure call is not
known until the time of the call at run time.
27
Discovering Knowledge
MOVING TOWARDS
OBJECT-ORIENTED PROGRAMMING
28
Discovering Knowledge
What is a class?
1. Class is a blueprint of object(s).
2 Objects created from the same class are similar but not the same.
3. The objects are similar because each has similar property type.
4. Each is different because the property value is different.
5. Analogy:
a. Cars built and assembled based on the same blueprint will
definitely look similar in design. However each car differs in
serial numbers, configuration, appearance, etc.
Car
blueprint
Actual cars
CLASS OBJECT(S)
35
Discovering Knowledge
Class Syntax
1. We know a classname if there is keyword “class” before the name.
2. The body of the class is enclosed in curly braces {}.
<access specifier>class ClassName{}3. Hence, the syntax of a class is:
4 An empty class is useless as it cannot be used to store any attribute or have
any behavior.
5. Hence, the body of a class should contain the following members:
1. One or more fields (a.k.a. attributes). public class ClassName {
2. One or more constructors.
3. One or more methods.
int field1;
String field2;
ClassName(){}
void method1(){}
String method2(int arg){}
}
36
Discovering Knowledge
Class Diagram
1. Class Diagram is a graphical representation of the actual class.
2. Because Class Diagram is more readable than code, it is often used to draft
the class design before the actual coding.
a. Designing solutions using diagram is easier and faster.
b. Validating the design is easier.
ClassName
field1:int
field2:String
method1():int
method2(arg:int):String
Class diagram
public class ClassName {
int field1;
String field2;
int method1(){}
String method2(int arg){}
}
Java code
37
public class Website {
String webName;
int webAge;
public static void main(String args[]){
//Creating objects
Website obj1 = new Website();
obj1.webName="Amazon";
obj1.webAge=4;
Website obj2 = new Website();
obj2.webName="Google";
obj2.webAge=14;
//Accessing object data through reference
System.out.println(obj1.webName+" "+obj1.webAge);
System.out.println(obj2.webName+" "+obj2.webAge);
}
}
Output:
Amazon 4
Google 14
ACTIVITY
Create a Student class with fields
name,reg_id,cgpa,semester and in main create 4 objects
with name Umar, Hasan,Maria, Anum and enter their
respective information there. Also display their relevant
information with their names:
Let’s see how can we take input from the user for the attributes we
have set in the class for various objects.
System.out.println("Enter your website");
obj1.webName=scVar.next();
System.out.println("Enter your WebAge");
obj1.webAge=scVar.nextInt();
System.out.println("Enter your website");
obj2.webName=scVar.next();
System.out.println("Enter your WebAge");
obj2.webAge=scVar.nextInt();
ACTIVITY:
Repeat the last activity for User Input
Discovering Knowledge
Class Diagram Components
1. Class diagram contains 4 segments:
a. The top segment is the class name.
b. Fields.
c. Constructor(s)
d. Method(s)
2. Because every class must have a constructor, it is understood that there should be one,
even if the constructor segment is sometimes omitted from the diagram.
<Class Name> Account
<Field(s)> customer: String
Account Nbr: int
<Constructor(s)>
<Method(s)> getBalance():double
Syntax Example
38
CONSTRUCTORS IN JAVA:
A constructor in Java is a block of code similar to a method that’s called when an
instance of an object is created. Here are the key differences between a constructor
and a method:
• A constructor doesn’t have a return type.
• The name of the constructor must be the same as the name of the class.
• Unlike methods, constructors are not considered members of a class.
• A constructor is called automatically when a new instance of an object is created.
Here’s the basic format for coding a constructor:
public ClassName (parameter-list)
{
statements...
}
The public keyword indicates that other classes can access the constructor.
ClassName must be the same as the name of the class that contains the
constructor. You code the parameter list the same way that you code it for a
method.
For Example:
Let’s see an example how we can create a constructor explicitly
public Actor(String first, String last)
{
firstName = first;
lastName = last;
}
Actor a = new Actor("Arnold", " Schwarzenegger"); //CALLING CONSTRUCTOR
If you do not provide a constructor for a class, Java will automatically create a
default constructor that has no parameters and doesn’t initialize any fields. This
default constructor is called if you specify the new keyword without passing
parameters.
For example:
Ball b = new Ball(); //CALLING DEFAULT CONSTRUCTOR
Here, a variable of type Ball is created by using the default constructor for the Ball
class.
For Example: Here passing argument to the constructor while calling it
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
public static void main(String []args) {
// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
} OUTPUT:
Passed Name is :tommy
Accessing Instance Variables and Methods
Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path.
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}
public void setAge( int age ) {
puppyAge = age;
}
public int getAge( ) {
System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}
public static void main(String []args) {
/* Object creation , passing name to constructor*/
Puppy myPuppy = new Puppy( "tommy" );
/* Call class method to set puppy's age */
myPuppy.setAge( 2 );
/* Call another class method to get puppy's age */
myPuppy.getAge( );
/* You can access instance variable as follows as well */
System.out.println("Variable Value :" + myPuppy.puppyAge );
}
} OUTPUT:
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
CLASS WORK:
Repeat the last program when you have to take the
values from the User, i.e Puppy’s name and age.
NAMED METHODS :
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
• public static − modifier
• int − return type
• methodName − name of the method
• a, b − formal parameters
• int a, int b − list of parameters
/* the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
Discovering Knowledge
Practical example 1
public class Account
Account
customer: String
Balance: double
getBalance():double
Class diagram
{
from
diagram to
code
}
String customer;
double balance;
double getBalance()
{
return balance;
}
Java code
39
Discovering Knowledge
Practical example 2
public class BMI {
double weight;
double height;
BMI
weight: double
height: double
getInput() : void
calculateBMI(): double
findStatus(): String
printStatus(): void
Class diagram
from
diagram to
code
Java code
}
void getInput() {
weight =
input.nextDouble();
height =
input.nextDouble();
}
double calculateBMI() {
return
weight/(height*height)*703;
}
String findStatus(){
//follow the criteria
return status;
}
void printStatus() {
S.O.P(bmi and status);
}
40
Discovering Knowledge
Class Diagram and Algorithm
1. Usually a comment box is used as a label to further describe the
algorithm applied to a particular method.
Student
name: String
Algorithm:
greet():void 1. Print “Hello” and student name.
class Student{
String name;
void greet(){
System.out.print(“Hello” + name);
}
}
41
Discovering Knowledge
Application Class
1. Application class is also known by other names
such as Driver , Test, Main or Launcher class.
2. Application class is a class that contains the
main method.
• public static void main(String [] args){}
3. Not every class will contain the main method.
4. If a program is made up of only one class, that
class definitely has to become the application
class.
5. If a program is made up of many classes, only
one of the classes need to be the application
class.
6 Application class will be the first class loaded
and executed.
ClassName
+main(String[] args):void
Example 1
Student
name: String
greet():void
+main(String[] args):void
Example 2
42
Discovering Knowledge
Application Class
1. Student class is an application class because it contains the
main method.
2. Hence, when the program runs, it will seek for the first line of
code in the main method and execute in a top-down manner.
Student
name: String
main():void
greet():void
Algorithm:
1. Create Student object.
2. Invoke method greet()
3. End
Algorithm:
1. Print “Hello” and name.
43
Discovering Knowledge
Discussion: Class Members
class Country {
String name = “Pakistan";
public static void main(String[] args){
Country pakistan = new Country();
pakistan.greet();
}
void greet(){
System.out.println(“Welcome to " + name);
}
}
1. Describe what happens within the main method.
2. Describe what happens within the greet() method.
3. Is this programming object-oriented? How do you know?
44
Discovering Knowledge
Discussion: Class Members
class Country {
String name = “Pakistan";
public static void main(String[] args){
Country pakistan = new Country();
pakistan.greet();
}
void greet(){
System.out.println(“Welcome to " + name);
}
}
This step creates an object called pakistan from Country class.
What does the object pakistan do?
45
Discovering Knowledge
Discussion: Class Members
class Country {
String name = “Pakistan";
public static void main(String[] args){
Country pakistan = new Country ();
pakistan.greet();
}
void greet(){
System.out.println(“Welcome to " + name);
}
}
Can the method access the field’s value?
What is the output?
46
Discovering Knowledge
Accessing Class Members
1. Fields and methods are object members.
2. Object members are accessible using the dot notation.
3. Note that members are accessible through object variable,
not through class.
4. E.g.:
Car myCar = new Car(“AXE8888”);
myCar.engineNo = “MGH05GX100085”;
myCar.changeOwner(“Akram”);
47
Discovering Knowledge
Accessing Class Members
Question:
Can I use
Car.engineNo = “MGH05GX100085”;
Why and why not?
48
Discovering Knowledge
Importing and Using Foreign Classes
1 package finance;
2 import java.util.Date;
3 // Additional import statements if required
4 class Stock {
7 // Implementation of the stock class
8 }
• Where declared?
• When required?
• import java.util.*;
• The java.lang package
49
Discovering Knowledge
Summary
• Abstraction: Eliminate the irrelevant, amplify the
essential.
• Encapsulation: Hiding the unnecessary.
• Inheritance: Modeling the simplicity.
• Polymorphism: Same function different behaviour.
• Class is a blueprint/template of object(s).
• Class contains constructor so that the class can be
used to create new object(s).
• Class contains fields to store values that can be used
to describe the object.
• Class contains methods to allow operations that
modify the values held by fields.
50
Ad

Recommended

oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
15 padrões de mensageria para integração de sistemas
15 padrões de mensageria para integração de sistemas
Helder da Rocha
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
CS3391 -OOP -UNIT – IV NOTES FINAL.pdf
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
[EMPOWERMENT TECHNOLOGIES]-ADVANCED PRESENTATION SKILLS
[EMPOWERMENT TECHNOLOGIES]-ADVANCED PRESENTATION SKILLS
JazzyNF
 
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
pkaviya
 
Introduction to Object Oriented Programming
Introduction to Object Oriented Programming
Moutaz Haddara
 
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
CS3391 -OOP -UNIT – I NOTES FINAL.pdf
AALIM MUHAMMED SALEGH COLLEGE OF ENGINEERING
 
classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Fragment
Fragment
nationalmobileapps
 
OOPS In JAVA.pptx
OOPS In JAVA.pptx
Sachin33417
 
Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Oop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Object oriented programming
Object oriented programming
Amit Soni (CTFL)
 
Java buzzwords
Java buzzwords
ramesh517
 
Java variable types
Java variable types
Soba Arjun
 
Basic concepts of object oriented programming
Basic concepts of object oriented programming
Sachin Sharma
 
Functions in C
Functions in C
Kamal Acharya
 
Type conversion
Type conversion
PreethaPreetha5
 
Exception Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Characteristics of OOPS
Characteristics of OOPS
abhishek kumar
 
Arrays in Java
Arrays in Java
Naz Abdalla
 
OOP java
OOP java
xball977
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
wrushabhsirsat
 
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
akashsachu221
 

More Related Content

What's hot (20)

classes and objects in C++
classes and objects in C++
HalaiHansaika
 
Fragment
Fragment
nationalmobileapps
 
OOPS In JAVA.pptx
OOPS In JAVA.pptx
Sachin33417
 
Templates in c++
Templates in c++
ThamizhselviKrishnam
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Oop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Object oriented programming
Object oriented programming
Amit Soni (CTFL)
 
Java buzzwords
Java buzzwords
ramesh517
 
Java variable types
Java variable types
Soba Arjun
 
Basic concepts of object oriented programming
Basic concepts of object oriented programming
Sachin Sharma
 
Functions in C
Functions in C
Kamal Acharya
 
Type conversion
Type conversion
PreethaPreetha5
 
Exception Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Characteristics of OOPS
Characteristics of OOPS
abhishek kumar
 
Arrays in Java
Arrays in Java
Naz Abdalla
 
OOP java
OOP java
xball977
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
classes and objects in C++
classes and objects in C++
HalaiHansaika
 
OOPS In JAVA.pptx
OOPS In JAVA.pptx
Sachin33417
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
C++ OOPS Concept
C++ OOPS Concept
Boopathi K
 
Oop c++class(final).ppt
Oop c++class(final).ppt
Alok Kumar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Object oriented programming
Object oriented programming
Amit Soni (CTFL)
 
Java buzzwords
Java buzzwords
ramesh517
 
Java variable types
Java variable types
Soba Arjun
 
Basic concepts of object oriented programming
Basic concepts of object oriented programming
Sachin Sharma
 
Characteristics of OOPS
Characteristics of OOPS
abhishek kumar
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 

Similar to Fundamentals of OOP (Object Oriented Programming) (20)

gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
wrushabhsirsat
 
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
akashsachu221
 
L1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdf
BhanuJatinSingh
 
Lecture 1.pptx
Lecture 1.pptx
IndraKhatri
 
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
ApurvaLaddha
 
object oriented programing lecture 1
object oriented programing lecture 1
Geophery sanga
 
CPP-Unit 1.pptx
CPP-Unit 1.pptx
YashKoli22
 
Unit_2.00000000000000000000000000000.pdf
Unit_2.00000000000000000000000000000.pdf
pateltech13
 
Chapter 02 The Object Model_Software E.ppt
Chapter 02 The Object Model_Software E.ppt
AhammadUllah3
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
uzairrrfr
 
Principles of OOPs.pptx
Principles of OOPs.pptx
LakshyaChauhan21
 
Object oriented programming
Object oriented programming
baabtra.com - No. 1 supplier of quality freshers
 
Introduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Mca 504 dotnet_unit3
Mca 504 dotnet_unit3
Rai Saheb Bhanwar Singh College Nasrullaganj
 
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
berihun18
 
Share Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
Benefits of encapsulation
Benefits of encapsulation
Muhammad Nawzir Khan
 
Ooad ch 2
Ooad ch 2
anujabeatrice2
 
1.3 Object Oriented Programming Paradigm, Basic Concepts of Object-Oriented P...
1.3 Object Oriented Programming Paradigm, Basic Concepts of Object-Oriented P...
VikasNirgude2
 
gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
gxhrehsrejhvytftfltyflytdtydtydky5dyrdtrdrdtrd
wrushabhsirsat
 
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
Java Fundamentalojhgghjjjjhhgghhjjjjhhj.ppt
akashsachu221
 
L1-Introduction to OOPs concepts.pdf
L1-Introduction to OOPs concepts.pdf
BhanuJatinSingh
 
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
UNIT1- OBJECT ORIENTED PROGRAMMING IN JAVA- AIML IT-SPPU
ApurvaLaddha
 
object oriented programing lecture 1
object oriented programing lecture 1
Geophery sanga
 
CPP-Unit 1.pptx
CPP-Unit 1.pptx
YashKoli22
 
Unit_2.00000000000000000000000000000.pdf
Unit_2.00000000000000000000000000000.pdf
pateltech13
 
Chapter 02 The Object Model_Software E.ppt
Chapter 02 The Object Model_Software E.ppt
AhammadUllah3
 
OOP02-27022023-090456am.pptx
OOP02-27022023-090456am.pptx
uzairrrfr
 
Introduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
chapterOne.pptxFSdgfqdzwwfagxgghvkjljhcxCZZXvcbx
berihun18
 
Share Unit 1- Basic concept of object-oriented-programming.ppt
Share Unit 1- Basic concept of object-oriented-programming.ppt
hannahrroselin95
 
1.3 Object Oriented Programming Paradigm, Basic Concepts of Object-Oriented P...
1.3 Object Oriented Programming Paradigm, Basic Concepts of Object-Oriented P...
VikasNirgude2
 
Ad

Recently uploaded (20)

LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Paper 107 | From Watchdog to Lapdog: Ishiguro’s Fiction and the Rise of “Godi...
Rajdeep Bavaliya
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
Ad

Fundamentals of OOP (Object Oriented Programming)

  • 2. Discovering Knowledge Gentle Reminder “Switch Off” your Mobile Phone Or Switch Mobile Phone to “Silent Mode” 2
  • 3. Discovering Knowledge Fundamentals of Object Oriented Programming 3
  • 4. Discovering Knowledge OOP PARADIGM • Emphasis on objects (what objects are needed in this program?) rather than procedure (what does this program need to do?). • Programs are divided into entities known as classes of objects. • Data Structures are designed such that they characterize objects. • Functions that operate on data of an object are tied together in data structures. • Data is hidden and cannot be accessed by external functions. • Objects communicate with each other through functions. • New data and functions can be easily added whenever necessary. • Follows bottom up approach in program design. 4
  • 5. Discovering Knowledge Organization of Data and Functions in OOP Data Member Function Member Function ©
  • 6. Discovering Knowledge Basic Concepts in OOP • Objects • Classes • Message Passing • Abstraction • Encapsulation • Inheritance • Polymorphism • Dynamic Binding 6
  • 7. Discovering Knowledge Objects • Objects are the basic run-time entities of an object oriented system. • They may represent a person, a place or any item that the program must handle. • Example Representation of an object 7
  • 8. Discovering Knowledge Objects Objects are made up of two "things": • State (a.k.a. attributes/fields/properties + value) - A given set of data which describes the object - e.g., colour,size,amount,name,phoneNumber,etc... • Behaviour (a.k.a. methods or functions) - A set of operations that the object can perform - e.g., walk, run, drive, sell, buy, transfer, computeTotal, open, close, etc… Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming. 8
  • 9. Discovering Knowledge Example of Object,State,Behaviour 9
  • 10. Discovering Knowledge Classes • A class defines the type of an object. • A class is a prototype/template or a blue print of an object. • A class is a specification, common to all objects of a particular type. • This specification contains the details of the data and functions that act upon the data.(data+functions) • Objects of a class are called individual instances of that class. • Any number of objects can be created based on a class. 10
  • 11. Discovering Knowledge Classes • We can create object of a class using following syntax, • Syntax: ClassName objectName; • Here ClassName is a class which is already defined and objectName is any user-defined name. • For example, if Student is a class, Student shahid, kamran; In the example, shahid and kamran are the names of the objects of class Student. We can declare/create any number of objects of a class. 11
  • 12. Discovering Knowledge Classes • Diagram showing the relationship between Classes and Objects • Other examples of classes are: Instructor, Student, Room, University, Car, etc. go to slide Number 28 12
  • 13. Discovering Knowledge Message Passing • A message for an object is a request for execution of a procedure and therefore will invoke a function in the receiving object that generates the desired result. • Message passing involves specifying the name of the object, the name of the function i.e. message and the information to be sent. • Objects can communicate with each other by passing messages same as people pass messages to each other. • Objects can send or receive messages or information. • Concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. 13
  • 14. Discovering Knowledge Message Passing • For example, consider two classes Product and Order. The object of the Product class can communicate with the object of the Order class by sending a request for placing order. 14
  • 15. Discovering Knowledge Abstraction • Abstraction refers to the representation of necessary features without including details or explanations. • Classes use the concept of abstraction and are defined as a list of abstract attributes and functions to operate on these attributes. • Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. - Implementation denotes how variables are declared, how functions are coded, etc. It is through interface (function header/function signature) a communication is sent to the object as messages. 15
  • 16. Discovering Knowledge Abstraction • When you press a key on your keyboard the character appears on the screen, you need to know only this, but How exactly it works electronically, is not needed. • Another Example is when you use the remote control of your TV, you do not bother about how pressing a key in the remote changes the channel on the TV. You just know that pressing the + volume button will increase the volume. 16
  • 17. Discovering Knowledge Encapsulation • Encapsulation is the principle of object-oriented programming. • In simple words, “Encapsulation is a process of binding data members (variables, properties) and member functions (methods) into a single unit”. 17
  • 18. Discovering Knowledge Encapsulation • The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. • These functions provide the interface between the objects data and the program. This insulation of the data from direct access by the program is called data hiding or information hiding. • A Class is the best example of encapsulation. 18
  • 19. Discovering Knowledge Encapsulation For example: Medical store • Lets say you have to buy some medicines. You go to the medical store and ask the chemist for the medicines. • Only the chemist has access to the medicines in the store based on your prescription. • The chemist knows what medicines to give to you. • This reduces the risk of you taking any medicine that is not intended for you. In this example, • Medicines Æ Member Variables. • Giving Medicine by Chemist Æ Member Methods. • You Æ External Application or piece of Code. 19
  • 20. Discovering Knowledge Difference between Abstraction and Encapsulation S# Abstraction Encapsulation 1 Abstraction solves the problem in Encapsulation solves the problem in the the design level. implementation level. 2 Abstraction is used for hiding the Encapsulation means hiding the code and unwanted data and giving relevant data into a single unit to protect the data data. from outside world. 3 Abstraction lets you focus on what Encapsulation means hiding the internal the object does instead of how it details or mechanics of how an object does it. does something. 4 Abstraction- Outer layout, used in terms of design. For Example:- Outer Look of a Mobile Phone, like it has a display screen and keypad buttons to dial a number. Encapsulation- Inner layout, used in terms of implementation. For Example:- Inner Implementation details of a Mobile Phone, how keypad button and Display Screen are connected with each other using circuits. 20
  • 21. Discovering Knowledge Inheritance • Inheritance is the process by which object of one class acquire the properties of objects of another class. • In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. • This is possible by deriving a new class from the existing one. The new class will have combined features of both the classes. 21
  • 22. Discovering Knowledge Inheritance • For Example: • Consider an example of family of three members having a mother, father & son named Jack. • Jack father : tall and dark • Jack mother: Short and fair • Jack is tall and fair,so he is said to have inherited the features of his father and mother respectively. 22
  • 23. Discovering Knowledge Inheritance • Through effective use of inheritance, you can save a lot of time in your programming and also reduce error. • Which in turn will increase the quality of work and productivity. • We will explain all of the above in detail later when we cover Inheritance. 23
  • 24. Discovering Knowledge Polymorphism • Polymorphism is an important OOP concept. • Polymorphism is a Greek term which means the ability to take more than one form. • In polymorphism an operation may show different behavior in different instances. Poly Morphism Polymorphism (Many) (Forms) (Many Forms) 24
  • 25. Discovering Knowledge Polymorphism • For example, + is used to make sum of two numbers as well as it is used to combine two strings. • This is known as operator overloading because same operator may behave differently on different instances. 25
  • 26. Discovering Knowledge Polymorphism • Same way functions can be overloaded. • For example, sum()function may take two arguments or three arguments etc. - i.e. sum (5, 7) or sum (4, 6, 8). • Single function Draw() draws different objects. 26
  • 27. Discovering Knowledge Dynamic Binding • Dynamic Binding is the process of linking of the code associated with a procedure call at the run-time”. • Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run time. 27
  • 29. Discovering Knowledge What is a class? 1. Class is a blueprint of object(s). 2 Objects created from the same class are similar but not the same. 3. The objects are similar because each has similar property type. 4. Each is different because the property value is different. 5. Analogy: a. Cars built and assembled based on the same blueprint will definitely look similar in design. However each car differs in serial numbers, configuration, appearance, etc. Car blueprint Actual cars CLASS OBJECT(S) 35
  • 30. Discovering Knowledge Class Syntax 1. We know a classname if there is keyword “class” before the name. 2. The body of the class is enclosed in curly braces {}. <access specifier>class ClassName{}3. Hence, the syntax of a class is: 4 An empty class is useless as it cannot be used to store any attribute or have any behavior. 5. Hence, the body of a class should contain the following members: 1. One or more fields (a.k.a. attributes). public class ClassName { 2. One or more constructors. 3. One or more methods. int field1; String field2; ClassName(){} void method1(){} String method2(int arg){} } 36
  • 31. Discovering Knowledge Class Diagram 1. Class Diagram is a graphical representation of the actual class. 2. Because Class Diagram is more readable than code, it is often used to draft the class design before the actual coding. a. Designing solutions using diagram is easier and faster. b. Validating the design is easier. ClassName field1:int field2:String method1():int method2(arg:int):String Class diagram public class ClassName { int field1; String field2; int method1(){} String method2(int arg){} } Java code 37
  • 32. public class Website { String webName; int webAge; public static void main(String args[]){ //Creating objects Website obj1 = new Website(); obj1.webName="Amazon"; obj1.webAge=4; Website obj2 = new Website(); obj2.webName="Google"; obj2.webAge=14; //Accessing object data through reference System.out.println(obj1.webName+" "+obj1.webAge); System.out.println(obj2.webName+" "+obj2.webAge); } } Output: Amazon 4 Google 14
  • 33. ACTIVITY Create a Student class with fields name,reg_id,cgpa,semester and in main create 4 objects with name Umar, Hasan,Maria, Anum and enter their respective information there. Also display their relevant information with their names:
  • 34. Let’s see how can we take input from the user for the attributes we have set in the class for various objects. System.out.println("Enter your website"); obj1.webName=scVar.next(); System.out.println("Enter your WebAge"); obj1.webAge=scVar.nextInt(); System.out.println("Enter your website"); obj2.webName=scVar.next(); System.out.println("Enter your WebAge"); obj2.webAge=scVar.nextInt();
  • 35. ACTIVITY: Repeat the last activity for User Input
  • 36. Discovering Knowledge Class Diagram Components 1. Class diagram contains 4 segments: a. The top segment is the class name. b. Fields. c. Constructor(s) d. Method(s) 2. Because every class must have a constructor, it is understood that there should be one, even if the constructor segment is sometimes omitted from the diagram. <Class Name> Account <Field(s)> customer: String Account Nbr: int <Constructor(s)> <Method(s)> getBalance():double Syntax Example 38
  • 37. CONSTRUCTORS IN JAVA: A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. Here are the key differences between a constructor and a method: • A constructor doesn’t have a return type. • The name of the constructor must be the same as the name of the class. • Unlike methods, constructors are not considered members of a class. • A constructor is called automatically when a new instance of an object is created. Here’s the basic format for coding a constructor: public ClassName (parameter-list) { statements... }
  • 38. The public keyword indicates that other classes can access the constructor. ClassName must be the same as the name of the class that contains the constructor. You code the parameter list the same way that you code it for a method. For Example: Let’s see an example how we can create a constructor explicitly
  • 39. public Actor(String first, String last) { firstName = first; lastName = last; } Actor a = new Actor("Arnold", " Schwarzenegger"); //CALLING CONSTRUCTOR If you do not provide a constructor for a class, Java will automatically create a default constructor that has no parameters and doesn’t initialize any fields. This default constructor is called if you specify the new keyword without passing parameters. For example: Ball b = new Ball(); //CALLING DEFAULT CONSTRUCTOR Here, a variable of type Ball is created by using the default constructor for the Ball class.
  • 40. For Example: Here passing argument to the constructor while calling it public class Puppy { public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Passed Name is :" + name ); } public static void main(String []args) { // Following statement would create an object myPuppy Puppy myPuppy = new Puppy( "tommy" ); } } OUTPUT: Passed Name is :tommy
  • 41. Accessing Instance Variables and Methods Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path. This example explains how to access instance variables and methods of a class. public class Puppy { int puppyAge; public Puppy(String name) { // This constructor has one parameter, name. System.out.println("Name chosen is :" + name ); } public void setAge( int age ) { puppyAge = age; } public int getAge( ) { System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; }
  • 42. public static void main(String []args) { /* Object creation , passing name to constructor*/ Puppy myPuppy = new Puppy( "tommy" ); /* Call class method to set puppy's age */ myPuppy.setAge( 2 ); /* Call another class method to get puppy's age */ myPuppy.getAge( ); /* You can access instance variable as follows as well */ System.out.println("Variable Value :" + myPuppy.puppyAge ); } } OUTPUT: Name chosen is :tommy Puppy's age is :2 Variable Value :2
  • 43. CLASS WORK: Repeat the last program when you have to take the values from the User, i.e Puppy’s name and age.
  • 44. NAMED METHODS : Creating Method Considering the following example to explain the syntax of a method − Syntax public static int methodName(int a, int b) { // body } Here, • public static − modifier • int − return type • methodName − name of the method • a, b − formal parameters • int a, int b − list of parameters
  • 45. /* the snippet returns the minimum between two numbers */ public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }
  • 46. Discovering Knowledge Practical example 1 public class Account Account customer: String Balance: double getBalance():double Class diagram { from diagram to code } String customer; double balance; double getBalance() { return balance; } Java code 39
  • 47. Discovering Knowledge Practical example 2 public class BMI { double weight; double height; BMI weight: double height: double getInput() : void calculateBMI(): double findStatus(): String printStatus(): void Class diagram from diagram to code Java code } void getInput() { weight = input.nextDouble(); height = input.nextDouble(); } double calculateBMI() { return weight/(height*height)*703; } String findStatus(){ //follow the criteria return status; } void printStatus() { S.O.P(bmi and status); } 40
  • 48. Discovering Knowledge Class Diagram and Algorithm 1. Usually a comment box is used as a label to further describe the algorithm applied to a particular method. Student name: String Algorithm: greet():void 1. Print “Hello” and student name. class Student{ String name; void greet(){ System.out.print(“Hello” + name); } } 41
  • 49. Discovering Knowledge Application Class 1. Application class is also known by other names such as Driver , Test, Main or Launcher class. 2. Application class is a class that contains the main method. • public static void main(String [] args){} 3. Not every class will contain the main method. 4. If a program is made up of only one class, that class definitely has to become the application class. 5. If a program is made up of many classes, only one of the classes need to be the application class. 6 Application class will be the first class loaded and executed. ClassName +main(String[] args):void Example 1 Student name: String greet():void +main(String[] args):void Example 2 42
  • 50. Discovering Knowledge Application Class 1. Student class is an application class because it contains the main method. 2. Hence, when the program runs, it will seek for the first line of code in the main method and execute in a top-down manner. Student name: String main():void greet():void Algorithm: 1. Create Student object. 2. Invoke method greet() 3. End Algorithm: 1. Print “Hello” and name. 43
  • 51. Discovering Knowledge Discussion: Class Members class Country { String name = “Pakistan"; public static void main(String[] args){ Country pakistan = new Country(); pakistan.greet(); } void greet(){ System.out.println(“Welcome to " + name); } } 1. Describe what happens within the main method. 2. Describe what happens within the greet() method. 3. Is this programming object-oriented? How do you know? 44
  • 52. Discovering Knowledge Discussion: Class Members class Country { String name = “Pakistan"; public static void main(String[] args){ Country pakistan = new Country(); pakistan.greet(); } void greet(){ System.out.println(“Welcome to " + name); } } This step creates an object called pakistan from Country class. What does the object pakistan do? 45
  • 53. Discovering Knowledge Discussion: Class Members class Country { String name = “Pakistan"; public static void main(String[] args){ Country pakistan = new Country (); pakistan.greet(); } void greet(){ System.out.println(“Welcome to " + name); } } Can the method access the field’s value? What is the output? 46
  • 54. Discovering Knowledge Accessing Class Members 1. Fields and methods are object members. 2. Object members are accessible using the dot notation. 3. Note that members are accessible through object variable, not through class. 4. E.g.: Car myCar = new Car(“AXE8888”); myCar.engineNo = “MGH05GX100085”; myCar.changeOwner(“Akram”); 47
  • 55. Discovering Knowledge Accessing Class Members Question: Can I use Car.engineNo = “MGH05GX100085”; Why and why not? 48
  • 56. Discovering Knowledge Importing and Using Foreign Classes 1 package finance; 2 import java.util.Date; 3 // Additional import statements if required 4 class Stock { 7 // Implementation of the stock class 8 } • Where declared? • When required? • import java.util.*; • The java.lang package 49
  • 57. Discovering Knowledge Summary • Abstraction: Eliminate the irrelevant, amplify the essential. • Encapsulation: Hiding the unnecessary. • Inheritance: Modeling the simplicity. • Polymorphism: Same function different behaviour. • Class is a blueprint/template of object(s). • Class contains constructor so that the class can be used to create new object(s). • Class contains fields to store values that can be used to describe the object. • Class contains methods to allow operations that modify the values held by fields. 50