The document discusses object-oriented programming concepts including objects, classes, message passing, abstraction, encapsulation, inheritance, polymorphism, and dynamic binding. It provides examples and definitions for each concept. It also covers basic class concepts like defining classes, creating objects, using constructors, and accessing instance variables and methods. The document appears to be teaching material for an introductory object-oriented programming course.
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
Objects
• Objectsare 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 aremade 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
Classes
• Aclass 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
• Wecan 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
• Diagramshowing 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
• Abstractionrefers 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
• Whenyou 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
• Encapsulationis 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
• Thedata 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 betweenAbstraction 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
• Inheritanceis 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
• ForExample:
• 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
• Througheffective 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
• Polymorphismis 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
• Forexample, + 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
• Sameway 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
Discovering Knowledge
What isa 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 Studentclass 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 howcan 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();
Discovering Knowledge
Class DiagramComponents
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:
Aconstructor 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 keywordindicates 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: Herepassing 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 Variablesand 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 voidmain(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 thelast program when you have to take the
values from the User, i.e Puppy’s name and age.
44.
NAMED METHODS :
CreatingMethod
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 snippetreturns 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 example1
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 example2
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 Diagramand 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: ClassMembers
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: ClassMembers
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: ClassMembers
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 ClassMembers
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
Importing andUsing 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