0% found this document useful (0 votes)
15 views34 pages

Wa0002.

Javaaa

Uploaded by

Yusuf Jamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views34 pages

Wa0002.

Javaaa

Uploaded by

Yusuf Jamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CSE201: Monsoon 2021, Section A

Advanced Programming

Lecture 01: Introduction to OOP

Vivek Kumar
Computer Science and Engineering
IIIT Delhi
vivekk@iiitd.ac.in
About me
• Bio
– http://vivkumar.github.io/
• Lab
– http://hipec.iiitd.edu.in/
Why Object Oriented Programming?

3
© Vivek Kumar
What is OOP?

It is a programming paradigm based on the concept of “objects”, which


may contain data in the form of fields, often known as attributes; and
code, in the form of procedures, often known as methods
(Wikipedia)
4
© Vivek Kumar
What is OOP?
class
car
Properties / Attributes Method
fuel reFuel() getFuel()
maxspeed setSpeed() getSpeed()

5
© Vivek Kumar
Advantages of OOP (1/3)
• Code reuse and recycling
– Objects can easily be reused

6
© Vivek Kumar
Advantages of OOP (2/3)
• Design benefits
– Extensive planning phase results better design and
lesser flaws

Car Engine
engine cylinders
Drive() Start()
7
© Vivek Kumar
Advantages of OOP (3/3)
• Software maintenance
– Easy to incorporate changes in legacy code (e.g.,
supporting a new hardware)
• Simplicity

8
© Vivek Kumar
Key Features of OOP
• Abstraction
• Encapsulation
• Method overloading
• Inheritance
• Method overriding
• Polymorphism

9
© Vivek Kumar
Abstraction

The main thing


is How to drive
a car ……

How the car is


moving and how
the engine is
working, this
information is
hidden.

(Abstraction)

10
© Vivek Kumar
Encapsulation

Ohh.. I wish I
can change the
max speed of
this car

Internal details of
the car hidden from
the user

(Encapsulation)

11
© Vivek Kumar
Summary: Encapsulation v/s Abstraction
• An encapsulated object can be thought of as
a black box -- its inner workings are hidden
from the client
• The client invokes the interface methods of
the object, which manages the instance data

Client Methods
Abstraction lets you focus on what
the object does instead of how it
does, while encapsulation means
hiding the internal details of how Data
an object works
12
© 2004 Pearson Addison-Wesley. All rights reserved
Class
WhyWithout Encapsulation
Encapsulation?
MyClass
int data
String name void doSomething()
int getSomething()
OtherClass thing

The rest of your program...

No encapsulation
Class
WhyWithout Encapsulation
Encapsulation?
MyClass
int data
String name void doSomething()
int getSomething()
OtherClass thing

The rest of your program...

No encapsulation
Class Supporting Encapsulation
Why Encapsulation?
MyClass
int data
String name void doSomething()
int getSomething()
OtherClass thing

/* interface methods */

The rest of your program...

Encapsulation
Visibility Modifier

public private

Variables
Violate Enforce
encapsulation encapsulation

Support other
Methods
Provide services
methods in the
to clients
class

16
© 2004 Pearson Addison-Wesley. All rights reserved
Accessors and Mutators
• Because instance data is private, a class usually
provides services to access and modify data values
• An accessor method returns the current value of a
variable
• A mutator method changes the value of a variable
• The names of accessor and mutator methods take the
form getX and setX, respectively, where X is the
name of the value
• They are sometimes called “getters” and “setters”

Wait, but why do we need “setter” when we are talking about


restricting accesses to fields from outside world ?
17
© 2004 Pearson Addison-Wesley. All rights reserved
Mutator Restrictions
• The use of mutators gives the class
designer the ability to restrict a client’s
options to modify an object’s state

• A mutator is often designed so that the


values of variables can be set only within
particular limits

18
© 2004 Pearson Addison-Wesley. All rights reserved
Procedural v/s OOP

19
A Sample Problem
• Write a method that will throw 2 Dice with
varying number of sides, a specified amount
of times, and reports how many times we got
a snake eyes (both dice showing 1)

• For example numSnakeEyes(6, 13, 100)


should return the number of snake eyes after
throwing a 6 sided Dice and 13 sided Dice
100 times
20
© 2004 Pearson Addison-Wesley. All rights reserved
Procedural (Structured) Programming
Approach
static Random rand = new Random();

static int roll(int numFaces) {


return 1 + rand.nextInt(numFaces);
}

static int numSnakeEyes(int sides1, int sides2, int numThrows) {


int count = 0;
for(int i = 0; i < numThrows; i++) {
int face1 = roll(sides1);
int face2 = roll(sides2);
if (face1 == 1 && face2 == 1)
count++;
}

return count;
} 21
© 2004 Pearson Addison-Wesley. All rights reserved
OOP Approach
• In OOP, we first focus on the main actors,
not how things are done.
• The main actors here are Dice objects. We
need to define a Dice class that captures
the state and behavior of a Dice.
• We can then instantiate as many dice
objects as we need for any particular
programs

22
© 2004 Pearson Addison-Wesley. All rights reserved
Classes (Recap)
• A class can contain data declarations and
method declarations
int size, weight;
Data declarations
char category;

Method declarations

23
© 2004 Pearson Addison-Wesley. All rights reserved
Dice Class

int faceValue;
Data declarations
int numFace;

roll()

setter() / getter() Method declarations

………

24
© 2004 Pearson Addison-Wesley. All rights reserved
public class Dice {
private final int numFaces; //maximum face value
private int faceValue; //current value showing on the dice

OOP // Constructor: Sets the initial face value.


public Dice(int _numFaces) {
numFaces = _numFaces;
Approach roll();
}

// Rolls the dice


public void roll() {
int curr_faceValue = 1 + rand.nextInt(numFaces);
setFaceValue(curr_faceValue);
}

// Face value setter/mutator.


private void setFaceValue (int value) {
if (value <= numFaces)
faceValue = value;
}
© 2004 Pearson Addison-Wesley. All rights reserved 25
// Face value getter/setter.
public int getFaceValue() {
return faceValue;
}
OOP
// Face value getter/setter.
Approach public int getNumFaces() {
return numFaces;
}

// Returns a string representation of this dice


public String toString() {
return “number of Faces “ + numFaces +
“current face value “ + faceValue);
}
} // End of Dice class

© 2004 Pearson Addison-Wesley. All rights reserved 26


static int numSnakeEyes(int sides1, int sides2,
int numThrows) {
Die die1 = new Die(sides1);
Die die2 = new Die(sides2);
OOP
Approach int count = 0;
for(int i = 0; i < numThrows; i++) {
die1.roll();
die2.roll();
The new if (die1.getFaceValue() == 1 &&
die2.getFaceValue() == 1 )
version count++;
}

return count;
}
© 2004 Pearson Addison-Wesley. All rights reserved 27
Instance Data
• We can depict the two Dice objects from
the RollingDice program as follows:
dice1 faceValue 5
numFaces 6

dice2 faceValue 2
numFaces 9

Each object maintains its own faceValue and


numFaces variable, and thus its own state
29
The toString Method
• All classes that represent objects should
define a toString method
• The toString method returns a
character string that represents the object
in some way
• It is called automatically when an object is
concatenated to a string or when it is
passed to the println method

© 2004 Pearson Addison-Wesley. All rights reserved 30


Another Sample Problem
• Coin example
– Write a program that flips two coins until one of
them comes up with heads three times in a
row, and report the winner

© 2004 Pearson Addison-Wesley. All rights reserved 31


Coin Class
public class Coin public boolean isHeads () {
{ return (face == HEADS);
private final int HEADS = 0; }
private final int TAILS = 1;
public String toString() {
private int face; String faceName;
if (face == HEADS)
public Coin () { faceName = "Heads";
flip(); else
} faceName = "Tails";
return faceName;
public void flip () { }
face = (int) (Math.random() * 2);
} } // end of class Coin

© 2004 Pearson Addison-Wesley. All rights reserved 32


// Flips two coins until one of them comes up
// heads three times in a row.
public static void main (String[] args) {
final int GOAL = 3;
int count1 = 0, count2 = 0;
// Create two separate coin objects
Coin coin1 = new Coin();
Coin coin2 = new Coin();
while (count1 < GOAL && count2 < GOAL)
{
FlipRace coin1.flip();
coin2.flip();
// Print the flip results (uses Coin's toString method)
System.out.print ("Coin 1: " + coin1);
System.out.println (" Coin 2: " + coin2);
// Increment or reset the counters
count1 = (coin1.isHeads()) ? count1+1 : 0;
count2 = (coin2.isHeads()) ? count2+1 : 0;
}
// Determine the winner
if (count1 < GOAL)
System.out.println ("Coin 2 Wins!");
else
if (count2 < GOAL)
System.out.println ("Coin 1 Wins!");
else
System.out.println ("It's a TIE!");
} // end of main()
© 2004 Pearson Addison-Wesley. All rights reserved 33
Summary
• What is OOP?
• Encapsulation
– Visibility modifiers
– Accessors and mutators
• Simple examples to understand the above
concepts
Next Class
• How to identify classes and objects in OOP

35

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy