0% found this document useful (0 votes)
3 views

JavaProgrammingForBeginners-CourseBook-81-90

The document explains Object-Oriented Programming (OOP) concepts, including classes, objects, and encapsulation. It provides examples of creating classes such as MotorBike and Book, demonstrating state and behavior, as well as the importance of access control through getters and setters. Additionally, it discusses the advantages of encapsulation, including data validation and code reuse.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

JavaProgrammingForBeginners-CourseBook-81-90

The document explains Object-Oriented Programming (OOP) concepts, including classes, objects, and encapsulation. It provides examples of creating classes such as MotorBike and Book, demonstrating state and behavior, as well as the importance of access control through getters and setters. Additionally, it discusses the advantages of encapsulation, including data validation and code reuse.

Uploaded by

gs23133
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Let's look at some OOP terminology.

A class is a template. An object is an instance of a class. In above example, Planet is a class. earth and venus
are objects.
name , location and distanceFromSun compose object state.

rotate() and revolve() define object's behavior.

Fields are the elements that make up the object state. Object behavior is implemented through Methods.
Each Planet has its own state:
name : "Earth", "Venus"

location : Each has its own orbit

distanceFromSun : They are at unique, different distances from the sun

Each has its own unique behavior:


rotate() : They rotate at different rates (and in fact, different directions!)

revolve() : They revolve round the sun in different orbits, at different speeds

Summary
In this step, we:
Understood how OOP is different from Prodedural Programming
Learned about a few basic OOP terms
Step 02: Programming Exercise PE-01
Exercises
In each of the following systems, identify the basic entities involved, and organize them using object oriented
terminology:
. Online Shopping System
. Person
Solution-1: Online Shopping System

Customer
name, address
login(), logout(), selectProduct(Product)

ShoppingCart
items
addItem(), removeItem()

Product
name, price, quantityAvailable
order(), changePrice()

Solution-2: Person
Person
name, address, hobbies, work
walk(), run(), sleep(), eat(), drink()

Step 03: Creating MotorBike class

In this series of examples, we want to model your pet mode of transport, a motorbike. We want to create motorbike
objects and play around with them.
We will start with two java files:
MotorBike.java, which contains the MotorBike class definition. This class will encapsulate our motorbike
state and behavior
MotorBikeRunner.java, with class MotorBikeRunner holding a main method, our program's entry point
Snippet-1: MotorBike Class
MotorBike.java

package com.in28minutes.oops;
public class MotorBike {
//behavior
void start() {
System.out.println("Bike started!");
}
}

MotorBikeRunner.java

package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();
}
}

Console Output
Bike started!
Bike started!
Snippet-1 Explained
We started off creating a simple MotorBike class with a start method. We created a couple of instances and
invoked the start method on them.
We created two classes because we believe in Seperation of Concerns :
MotorBike class is responsible for all its data and behavior.

MotorBikeRunner class is responsible for running MotorBike examples.

Summary
In this step, we:
Defined a MotorBike class allowing us to further explore OOP concepts in the next steps
Step 04: Programming Exercise OO-PE-02
Exercises
. Write a small Java program to create a Book class , and then create instances to represent the following
book titles:
"The Art Of Computer Programming"
"Effective Java"
"Clean Code"
Solution
Book.java

public class Book {


private String title;

public void setTitle(String bookTitle) {


title = bookTitle;
}

public String getTitle() {


return title;
}
}

BookRunner.java

public class BookRunner {


public static void main(String[] args) {
Book taocp = new Book();
taocp.setTitle("The Art Of Computer Programming");
Book ej = new Book();
ej.setTitle("Effective Java");
Book cc = new Book();
cc.setTitle("Clean Code");
System.out.println(taocp.getTitle());
System.out.println(ej.getTitle());
System.out.println(cc.getTitle());
}
}

Console Output
The Art Of Computer Programming
Effective Java
Clean Code
Step 05: MotorBike - Representing State
An object encapsulates both state and behavior.
State defines "the condition of the object at a given time". State is represented by member variables.
In the MotorBike example, if we need a speed attribute for each MotorBike , here is how we would include it.
Snippet-1 : MotorBike with state variable speed
MotorBike.java

package com.in28minutes.oops;

public class MotorBike {


int speed;
void start() {
System.out.println("Bike started!");
}
}

MotorBikeRunner.java

package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();

ducati.speed = 100;
honda.speed = 80;
ducati.speed = 20;
honda.speed = 0;
}
}

Console Output
Bike started!
Bike started!
Snippet-4 Explained
int speed; within MotorBike , defines a member variable.
It can be accessed within objects such as ducati and honda , by qualifying it with the object name ( ducati or
honda ).

ducati.speed = 100;
honda.speed = 80;

ducati has its own value for speed , and so does honda . These values are independent of each other. Changing
one does not affect the other.
Classroom Exercise CE-OO-01
. Update the Book class created previously to include a member variable named noOfCopies , and
demonstrate how it can be set and updated independently for each of the three titles specified earlier.
Solution
TODO
Step 07: MotorBike - get() and set() methods
In the previous step. we were merrily modifying the speed attribute within the ducati and honda objects directly,
from within the main() program.
public class MotorBikeRunner {
public static void main(String[] args) {
//... Other code
ducati.speed = 100;
honda.speed = 0;
}
}

This did work fine, but it breaks the fundamental principle of encapsulation in OOP.
"A method of one object, should not be allowed to directly access the state of another object. To do so, such an
object should only be allowed to invoke methods on the target object".
In other words, a member variable should not be directly accessible from methods declared outside its class .
Snippet-3 : MotorBike class with private attributes
MotorBike.java

package com.in28minutes.oops;

public class MotorBike {


private int speed;

void start() {
System.out.println("Bike started!");
}

void setSpeed(int speed) {


this.speed = speed;
}
}

MotorBikeRunner.java

package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();

ducati.setSpeed(100);
honda.setSpeed(80);

ducati.setSpeed(20);
honda.setSpeed(0);
}
}

Console Output
Bike started!
Bike started!
Snippet-3 Explained
By declaring speed as private , we provide MotorBike with something called access control. Java keywords
such as public and private are called access modifiers. They control what external objects can access within a
given object.
Let's look at this.speed = speed; in the body of method setSpeed() :
An member variable always belongs to a specific instance of that class .
A method argument behaves just like a local variable inside that method.
To differentiate between the two, this is used. The expression this.speed refers to the member variable
speed of a Motorbike object. setSpeed() would be invoked on that very object.

Code written earlier within MotorBikeRunner , such as ducati.speed = 100; would now result in errors! The
correct way to access and modify speed is to invoke appropriate methods such as setSpeed() , on MotorBike
objects.
Classroom Exercise CE-OO-02
. Update the class Book to make sure it no longer breaks Encapsulation principles.
Solution
TODO
Summary
In this step, we:
Learned about the need for access control to implement encapsulation
Observed that Java provides access modifiers (such as public and private ) for such control
Understood the need for get() and set() methods to access object data

Step 08: Accessing Object State


Encapsulation is needed to protect an object's state from direct access by other objects. We were able to protect
the state of MotorBike objects by declaring speed to be private . We have created a sort of rigid situation here,
since the private declaration of speed forbids even a get access. How do we address this issue? Again, the
answer is to provide a method for reading the current speed .
Snippet-4 : getSpeed() of MotorBike
MotorBike.java

package com.in28minutes.oops;

public class MotorBike {


//Same as before

int getSpeed() {
return this.speed;
}
}
MotorBikeRunner.java

package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();

ducati.setSpeed(100);
honda.setSpeed(80);
System.out.printf("Current Ducati Speed is : %d", ducati.getSpeed()).println();
System.out.printf("Current Honda Speed is : %d", honda.getSpeed()).println();
}
}

Console Output
Bike started!
Bike started!
Current Ducati Speed is : 100
Current Honda Speed is : 80
Snippet-4 Explained
Defining a method such as getSpeed() allows us to access the current speed of a MotorBike object.
int getSpeed() {
return this.speed;
}

Eclipse has a very handy feature. When the state elements (member variables) of a class have been defined, it
can generate default get() and set() methods for each of them. You would want to use this regularly, to save on
time and typing effort. Right click on class > Generate Source > Generate Getters and Setters
Summary
In this step, we:
Understood how access control forces us to provide get() methods as well
Explored a few Eclispe tips to generate get() and set() versions for each class attribute
Step 10: Default Object State
What happens if a data element inside an object is not initialized with a value?
Snippet-5 : Default Initialization of Object State
MotorBike.java
//Same as before

MotorBikeRunner.java
package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike honda = new MotorBike();
System.out.printf("Current Honda Speed is : %d", honda.getSpeed()).println();
}
}

Console Output
Current Honda Speed is : 0
Snippet-6 Explained
When we instantiate an object, all its state elements are always initialized, to the default values of their types. Inside
MotorBike , speed is declared to be an int , and so is initialized to 0 . This happens even before any method of
MotorBike is called, including start() .

You can see that honda.getSpeed() printed 0 even though we did not explictly initialize it.
Default
Summary
In this step, we:
Learnt that default values are assigned to object member variables.
Step 10: Encapsulation: Its Advantages
At the heart of encapsulation, is the need to protect object's state. From whom? Other objects.
Let's look at an example to understand Encapsulation better.
Snippet-7 : Advantage of Encapsulation
MotorBike.java

package com.in28minutes.oops;

public class MotorBike {


private int speed;

public void start() {


System.out.println("Bike started!");
}

public void setSpeed(int speed) {


this.speed = speed;
}

public int getSpeed() {


return this.speed;
}
}

MotorBikeRunner.java
package com.in28minutes.oops;

public class MotorBikeRunner {

public static void main(String[] args) {


MotorBike ducati = new MotorBike();
ducati.start();
ducati.setSpeed(-100);
System.out.printf("Current Ducati Speed is : %d", ducati.getSpeed()).println();
}
}

Console Output
Bike started!
Current Ducati Speed is : -100
Snippet-01 Explained
For a motorbike, -100 might be an invalid speed. Currently, we do not have any validation. Having a method
setSpeed allows us to add validation.

Let's see how to do that.


Snippet-02 : Speed Validity Check
MotorBike.java

package com.in28minutes.oops;

public class MotorBike {

//Other code as is

public void setSpeed(int speed) {


if(speed > 0)
this.speed = speed;
}

MotorBikeRunner.java
//Same as before

The output of this snippet is:


Bike started!
Current Ducati Speed is : 0
Snippet-8 Explained
setSpeed() checks if(speed > 0) and does not update speed for negative values.
This is not perfect solution because the caller of the setSpeed method assumes that he was successful.
Ideally, we should throw an Exception indicating validation error. We will talk about Exceptions later.
Summary
In this step, we:
Explored the first advantage of encapsulation - A provision for adding data validation
Highlighted how such validation can be done, using the Motorbike example
Step 11: Encapsulation - Advantages (Code Reuse)
We've understood quite a few things about encapsulation under OOP.
Suppose at different points of time, we want to increase the speeds of both Honda and Ducati bikes by a fixed
amount, say 100 mph . The logic would be simple, right? Fetch the current speed of each bike, increment that
fetched value by 100 , and then set the new value back into that bike's speed . The following example puts the
above logic into action.
Snippet-1 : Bulky Speed Increment code
MotorBike.java
// No Change

MotorBikeRunner.java

package com.in28minutes.oops;

public class MotorBikeRunner {


public static void main(String[] args) {
MotorBike ducati = new MotorBike();
MotorBike honda = new MotorBike();
ducati.start();
honda.start();
ducati.setSpeed(100);

System.out.printf("Earlier Ducati Speed is : %d", ducati.getSpeed()).println();


System.out.printf("Earlier Honda Speed is : %d", honda.getSpeed()).println();

int ducatiSpeed = ducati.getSpeed();


ducatiSpeed = ducatiSpeed + 100;
ducati.setSpeed(ducatiSpeed);

int hondaSpeed = honda.getSpeed();


hondaSpeed = hondaSpeed + 100;
honda.setSpeed(hondaSpeed);

System.out.printf("Later Ducati Speed is : %d", ducati.getSpeed()).println();


System.out.printf("Later Honda Speed is : %d", honda.getSpeed()).println();
}
}

The output of this snippet is:


Bike started!
Bike started!
Earlier Ducati Speed is : 100
Earlier Honda Speed is : 0
Later Ducati Speed is : 200

You might also like