JavaProgrammingForBeginners-CourseBook-81-90
JavaProgrammingForBeginners-CourseBook-81-90
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.
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"
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()
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;
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.
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
BookRunner.java
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;
MotorBikeRunner.java
package com.in28minutes.oops;
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;
void start() {
System.out.println("Bike started!");
}
MotorBikeRunner.java
package com.in28minutes.oops;
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
package com.in28minutes.oops;
int getSpeed() {
return this.speed;
}
}
MotorBikeRunner.java
package com.in28minutes.oops;
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;
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;
MotorBikeRunner.java
package com.in28minutes.oops;
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.
package com.in28minutes.oops;
//Other code as is
MotorBikeRunner.java
//Same as before
MotorBikeRunner.java
package com.in28minutes.oops;