Introduction To OOP Concepts

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

LECTURE 3 Introduction to OOP concepts

OUTLINE
• Object Oriented Programming paradigm
• Concepts of Objects, Classes, Message Passing
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
PARADIGM OF OOP

• Programs are divided into entities Known as classes of objects.


• Major emphasis is on objects rather then procedures.
• Functions and Data Structures are required to design characteristics of objects.
• Data hiding is an important feature.
• Objects communicate with each other through functions.
• New data and functions can be easily added whenever necessary.
• Follows bottom up approach in program design.
OOP
Object-Oriented Programming or OOPs refers to languages that uses objects in
programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism etc. in programming.
The main aim of OOP is to bind together the data and the functions that operate on
them so that no other part of the code can access this data except that function.
BASIC PILLARS OF OOP
Bahria University Karachi Campus

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
Bahria University Karachi Campus

OBJECTS
Objects are made up of two "things":

• State (attributes/fields/properties + value)


• A given set of data which describes the object
• e.g., colour, size, amount, name, phoneNumber, etc...

• Behaviour (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.
Bahria University Karachi Campus

EXAMPLE OF OBJECT, STATE, BEHAVIOURS


CREATING AN OBJECT
Declaration − This is the very first step of object creation. In this step, you need to
declare a variable with the class name as the data type.
Instantiation − Next step is the instantiation where you need to use the ‘new’
keyword to create the object.
Initialization − Finally in the third step, you need to initialize the object by calling
the class constructor. 
Bahria University Karachi Campus

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
bluepri
nt
Actual cars

CLASS
OBJECT(S)
SYNTAX
class <class_name>{  
    field;  
    method;  
}  
/Defining a Student class.  
class Student{  
 //defining fields  
 int id;//field or data member or instance variable  
 String name;  
 //creating main method inside the Student class  
 public static void main(String args[]){  
  //Creating an object or instance  
  Student s1=new Student();//creating an object of Student  
  //Printing values of the object  
  System.out.println(s1.id);//accessing member through reference variable  
  System.out.println(s1.name);  
 }  
}  
Bahria University Karachi Campus

APPLICATION CLASS ClassName


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. +main(String[] args):void

• public static void main(String [ ] args){ }


Example 1
3. Not every class will contain the main method.
4. If a program is made up of only one class, that class Student

definitely has to become the application class. name: String


5. If a program is made up of many classes, only one of
the classes need to be the application class. greet():void

6. Application class will be the first class loaded and +main(String[] args):void
executed.
Example 2
HOW OBJECTS ARE CREATED
Vehicle minivan = new Vehicle();
Vehicle truck = new Vehicle();

Vehicle car1 = new Vehicle();


Vehicle car2 = car1;
Bahria University Karachi Campus

ACCESSING CLASS MEMBERS


1. Fields and methods are object members.
2. Object members are accessible using the dot operator.
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”);

Class Activity:
Can I use
Car.engineNo = “MGH05GX100085”;
Why and why not?
class Student{  
 int rollno;  
 String name;  
 void insertRecord(int r, String n){  
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){System.out.println(rollno+" "+name);}  
}  
class TestStudent4{  
 public static void main(String args[]){  
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
}  
EXAMPLE
create a class of student . Think of its properties and behaviors. Write it down.
Create an object s1 of student class. Save your name , enrolment num, age, address in
it . And call method of markattendance() for s1.
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
EXAMPLE minivan.mpg = 21;

// assign values to fields in sportscar


class Vehicle { sportscar.passengers = 2;
sportscar.fuelcap = 14;
int passengers; // number of passengers
sportscar.mpg = 12;
int fuelcap; // fuel capacity in gallons // compute the ranges assuming a full tank of gas
int mpg; // fuel consumption in miles per gallon range1 = minivan.fuelcap * minivan.mpg;
range2 = sportscar.fuelcap * sportscar.mpg;
}
class TwoVehicles { System.out.println("Minivan can carry " +
public static void main(String args[]) { minivan.passengers +
" with a range of " + range1);
Vehicle minivan = new Vehicle();
Vehicle sportscar = new Vehicle(); System.out.println("Sportscar can carry " +
int range1, range2; sportscar.passengers +
" with a range of " + range2);
ENCAPSULATION
Encapsulation simply means binding object state(fields) and behavior(methods)
together. If you are creating class, you are doing encapsulation.
 it is a protective shield that prevents the data from being accessed by the code
outside this shield.
As in encapsulation, the data in a class is hidden from other classes, so it is also
known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as private
and writing public methods in the class to set and get the values of variables.
INHERITANCE
It is the concept of one class to inherit properties from other class.
It helps to reuse the code and establish a relationship between different classes.
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
A class which inherits the properties is known as Child
Class whereas a class whose properties are inherited
is known as Parent class.  
SYNTAX OVERVIEW
class derived-class extends base-class Class teacher {
{
//methods and fields
} }
Class physicsteacher extends teacher{

}
Bahria University Karachi Campus
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.
•Which in turn will increase the quality of work
and productivity.
ABSTRACTION Bahria University Karachi Campus

•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.
Bahria University Karachi Campus

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.
Consider a real-life example of a man driving a car. The man only
knows that pressing the accelerators will increase the speed of car or
applying brakes will stop the car but he does not know about how
on pressing the accelerator the speed is actually increasing, he does
not know about the inner mechanism of the car or the
implementation of accelerator, brakes etc in the car. This is what
abstraction is.
In java, abstraction is achieved by interfaces and abstract classes.
We can achieve 100% abstraction using interfaces.
Bahria University Karachi Campus
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
does it. something.
4 Abstraction- Outer layout, used in Encapsulation- Inner layout, used in terms
terms of design. of implementation.
For Example:- For Example:- Inner Implementation
Outer Look of a Mobile Phone, like details of a Mobile Phone, how keypad
it has a display screen and keypad button and Display Screen are connected
buttons to dial a number. with each other using circuits.
Bahria University Karachi Campus

POLYMORPHISM Poly Morphism Polymorphism


(Many) (Forms) (Many Forms)

•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.
•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.
Bahria University Karachi Campus

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.


Bahria University Karachi Campus

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.
Bahria University Karachi Campus

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.
Bahria University Karachi Campus

MOVING TOWARDS
OBJECT-ORIENTED
PROGRAMMING
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…


public class MyClass {
public static void main(String[] • Structured
args){
code…
Programming
code… • Covered in
code… Lab1&2
code…
code…
code…
code…
code…
code…
code…
code…
code…
}
}
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…


public class BMI { • Structured
public static void main(String[] args){ Programming
Scanner input = new Scanner(System.in);
double bmi, weight, height; • BMI Exercise
S.O.P(“Enter weight in Pounds”);
weight = input.nextDouble();
S.O.P(“Enther height in Inches”);
height = input.nextDouble();
bmi = weight/(height*height)*703;
String status;
if(bmi < 18.5)
status = “underweight”;
else if(bmi < 24.9)
status = “normal”;// so on.
S.O.P(“You BMI is “+ bmi+
“your status is” + status);
}
}
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…

public class MyClass {


public static void main(String[] args) public static void other()
{ {
code… code…
code… code…
other(); code…
code… code…
code… }
andAnother(); public static void andAnother()
code… {
code… code…
} code…
• Procedural code…
Programming code…
}
• Covered in Lab3 }
(Next Week)
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…


public class MyClass {
public static void main(String[] args) public static double calculateBMI(double w,
{ double h) {
Scanner input = new Scanner(System.in); return w/(h*h)*703;
double bmi, weight, height; }
S.O.P(“Enter weight in Pounds”);
weight = input.nextDouble();
S.O.P(“Enther height in Inches”);
height = input.nextDouble(); public static String findStatus(double bmi)
bmi = calculateBMI(weight,height); {
S.O.P(“You BMI is “+ bmi+ String status;
“your status is” + findStatus(bmi)); if(bmi < 18.5)
status = “underweight”;
} else if(bmi < 25.0)
status = “normal”;// so on.
return status;
}
• Procedural Programming }// End MyClass
• BMI Exercise
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…


public class MyClass { public class MyOtherClass {
public static void main(String[] args) { public void aMethod() {
MyOtherClass m = new MyOtherClass(); code…
m.aMethod(); code…
AndAnotherClass a = new AndAnotherClass(); code…
a.aMethod(); code…
} }
} }

public class AndAnotherClass {


public void aMethod () {
code…
code…
• Object-Oriented Programming code…
• Covered in Lab4 and onward code…
}
}
Bahria University Karachi Campus

MOVING TOWARDS OBJECTS…


public class Application { public double calculateBMI() {
public static void main(String[] args) { return weight / (height*height)*703;
BMI bmi = new BMI(); }
bmi.getInput(); public String findStatus() {
bmi.printStatus(); String status=null;
} if(bmi < 18.5)
}// application class ends status = "underweight";
else if(bmi < 25.0)
public class BMI { status = "normal";// so on.
double weight, height,bmi; return status;
String status; }
public void printStatus() {
public void getInput() {
bmi = calculateBMI();
Scanner input = new Scanner(System.in);
S.O.P("You BMI is "+ bmi+
S.O.P("Enter weight in Pounds"); "your status is" + findStatus());
weight = input.nextDouble(); }
S.O.P("Enther height in Inches"); }//class BMI ends
height = input.nextDouble();
• Object-Oriented Programming
}
• BMI class exercise

You might also like