Object Oriented Programming
OOP allows you to easily decompose a problem into sub groups
of related parts. All OOP languages have 3 things in common:
- They
have objects - They
are polymorphism - And
they have inheritance
Let’s look at Objects
An object is a
logical entity containing data and the code that manipulate that data. Within
an object some of the code or data may be private to the object and
inaccessible by anything outside the object. In this way, an object provides a
significant level of protection against accidental modification or incorrect
use. This is referred to as encapsulation.
When we create a class we
give it a name and a class is divided in two sections. One piece is the
variable section and then the method (function) section. OOP allow you to hide
date from the eye of the programmer and only make the method available. The
method will obviously work with the variable its like making gates. Once step
is hiding the date and that is what w call encapsulation. It
will hide inside the class the variable. So we cannot reach the variable
directly. The method or function accesses the data. Secure data is one of the
most important elements in Computer Science. OOP is a secure heaven were the
data is protected. vs. structured programming like C use records struct is used in C to concatenate the
record. You can directly access that struct
. The data is behind the function Call a function that will touch the variable.
We have created private declaration and public declaration.
Let’s look at
polymorphism:
OOP languages support polymorphism which allows one name to
be used for several related but slightly different purposes. The purpose of
polymorphism is to let one name be used to specify the general class of action.
Depending on what type of data it is dealing with a specific instance of the
general case is executed. Example of polymorphism: http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/collec.html
In other word polymorphism
can be understood in one simple statement. You can have more then one method
with the same name. You can have the same function name for more then one
function. But how will it discriminates between function? The compiler will know depending on the number
of parameter passed into the function. Not only with the number. The compiler
is getting smarter to the fact that it knows which function to call. Before it
would know the difference based on the name of the function, but now the
compiler is more human-like i.e. cal_sum(int x, int y, int z) and
cal_sum(double x, double, y). The
description of the function, the kind of parameter and how many will define the
difference. A function will do an action if it does more then one action it
does a class of action, using the same function name. All of that was done with
improvement in the compiler.
Let’s talk about
inheritance:
Inheritance is the process by which an object can acquire
the properties of another object. This is important because t support the
concept of classification. Example, a “Red Delicious Apple” is part of a class
which is part of a fruit class, which is under the larger class of food. So without the use of classification, each
object would have to define all of its characters explicitly. Using this
classification, and object need only define qualities that makes it unique
within this class.
It is the inheritance mechanism that makes it possible for
one object to be a specific instance of a more general class.
While we declare classes inheriting
other classes an object should never directly manipulate the internal data of
another object. Therefore, all
communication should be via message sending, that is through method calls. The data in an object are usually called its
“instance variables” or “fields”, and the functions and procedures are called
its methods.
A specific object that is an instance of a class will have
specific values for its fields that define its current state.
If I declare a class Vehicle I know that a car can be a vehicle, a truck can be a
vehicle a train can be a vehicle
but if I look at the car, I can have
a GM, a Toyota etc. and what is common in a vehicle is the engine size,
therefore every variable that is common should be above and what is strictly
used by car for example should be at
the bottom. This is inheritance. I can create a class building and class floor
that will start inheriting all the date or function of the building and if I
want to make n office the office will be in a floor and in the building so the
office will inherited the properties of floor and building.
A specific instance is
truly specific because each object is specific to itself.
Important: A simple
rule of thumb in identifying class is to look for nouns in the problem
analysis. Methods on the other hand correspond to verbs (actions)
Anything that is a
noun in a programming will be transform into a class and every action will
appear as a method. First we have to declare our date type our type is
class a call you can not touch or work with and object is a declaration of that
class and that is what we call an instance of that class. I will create an
object of class, so you must declare a class and then call it an object.
<>
A programming example:
class
EmployeeTest {
public
static void main(String[] args) {
//Declaring
an object called number007 of class type Employee
//Employee.
Notice the use of new
Employee
number007 = new Employee(”James Bond”, 100000);
number007.raiseSalary(5);
number007.print();
}// end
of main
}//end of
EmployeeTest
//Here is
the actual definition of the class type Employee.
class
Employee {
// The
date (fields) declaration section.
private
String name;
private
double salary;
//The
counstructor definition. The special method is called
//the
time when the object is instantiated.
public Employee(String n, double s){
name =n;
//initializing name to passed parameter n.
salary=s;
//initializing name to passed parameter s.
}
//Declaring
the method print() that will printout the values:
public void print() {
System.out.println(name+”\t”+salary);
}//End of
method print()
//Declaring
another method called raisedSalary() that will
//Take as
input the percentage of the raise. It doesn’t return
//any
value. It only modifies the salary variable.
public
void raiseSalary(double byPercent) {
salary*=1
+ byPercent/100;
}//end of
method raiseSalary()
}//end of
class Employee declaration.
Note: It is possible to use the public keyboard with
your instance variables but it would be a very bad idea. Having public data
fields would allow any part of the program to read & modify the instance
variables. That completely ruins encapsulation! So keep them private.
The constructor:
Let’s look at the first method listed in the Employee class:
public Employee(String
n, double s){
name =n;
//initializing name to passed parameter n.
salary=s;
//initializing name to passed parameter s.
}
This is an example of constructor method that is used to
initialize objects of a class giving the instance variable the initial state
you want them to have.
Example: When you create an instance (object) of the
Employee class with code like this:
Employeenumber007 = new
Employee(”James Bond”, 100000);
The you have set
the instance fields foe the instance objects they are now related to
(number007) as follows”:
name=”James Bond” and
salary = 100000
Notice: the new keyword is always used together
with a constructor to create the object. This forces you to set the initial
state of your object. In Java, you cannot creates an instance of a class without initializing
it the instance variables (In Past OOP program this used to create runtime
error)
Please keep the following in mind:
1- A
constructor has the same name as the class
2- A
constructor may take one or more ( or even none) parameter
3- A
constructor is always called with the new
keyword
4- A
constructor has no return value
5- You
cannot apply a constructor to an existing objects to reset the instance to
“field”values
The constructor is used in one situation when you create
that lass and it is for every object that you create/ You need another object
internally control called new.
In java you create
the variable are created in memory. But you don’t have to worry about cleaning
up the ram. In java it cleans what it put in.
Let us look at this example what if we had more then one
employee??
We need an array of objects!!☺
class
EmployeeArray{
public
static void main(String[] args) {
//Cretaing
an array of objects
Employee[]statff
= new Employee[3]
//New
Instantiating the element in the array , one by one.
Staf[0] =
new Employee(“Harry Smith”,35000);
Staf[1] =
new Employee(“Sandy Bell”,75000);
Staf[3] =
new Employee(“Wendy Well”,54000);
int i
for(i=0;i<i++){
staff[i].raiseSalary(5) //To call a method of
an object we provide the object name “.”the method name .
staff[i].print();
}//end of
look
}/end of
main
}//end of
class
// Now we
define the class Employee
Class
Employee{
public
Employee(String n, double s)
name =n;
salary=x;
// the
print () method :
public
void print (){
System.out.println(name+”|t”+salary);
}
//the
raiseSalary() method:
public
void raiseSalary (double byPercent) {
Salary*=1+
ByPercent/100;
}
//You
canneither place the data fields of the class either at the beginning or at the end of the class definition
private
String name;
private
double salary;
}//end of
class definition.
More Example:
Let us take a look at this Java program that calculates the
Miles per Gallons a car spends:
import
java.io.*;// including the input-output library
class
MilesPerGallon{
public
static void main(String []args) {
//The following is used to input data from the
keyboard:
BufferedReader
userIn = new BufferedReader(new InputStreamReader(System.in));
// you
don’t have to memorize the above
String
line;
int
startMiles, endMiles;
double
gallons;
try{
System.out.println(”Enter
first reading”);
line =
userIn.readLine();// get the input
startMiles
= Integer.parseInt(line); //Parse input into integer value.
System.out.println(”Enter
second reading”);
line =
userIn.readLine();// get the input
endMiles
= Integer.parseInt( line );
System.out.println(”Enter
Gallons:”);
line =
userIn.readLine();
gallons =
Double.parseDouble(line);
//Declaring
an object called my car of class type Car
Car mycar
= new Car (startMiles,endMiles,gallons);
System.out.println(”Miles
per gallon=”+mycar.calculateMPG());
}//end of
main
catch
(Exception e) {
}//end of
class
}
}
class
Car{
//
instance variables
private
int sm; // starting odometer reading
private
int em; //ending odometer reading
private
double gallons; //gallons of gas used
//The
constructors
Car(int
first, int last, double gals){
sm =
first;
em =
last;
gallons =
gals;
}
//Methods
declared:
public
double calculateMPG( ){
return(
em - sm)/gallons;
}//end
class declaration
}
Try this program with following value:
200 - 450 - 2 =
125
Here is another example:
/*Constructor
Overloading:
Let us
take a look a this java program that will deal with constructor overloading.
Constructor
methods are not suppose to display anything but the println in this example
is placed
there to prove that depending on the number of arguments in this case a certain
constructor
is called by the compiler
*/
class
Point3D {
private
double x ;
private double y;
private double z;
Point3D(double
ax){
System.out.println (”We are in the
first counstructor”);
x =ax;
y = 1;
z = 1;
}
Point3D(double ax, double ay){
System.out.println (”We are
in the second counstructor”);
x =ax;
y = ay;
z = 1;
}
Point3D(double ax, double ay, double az){
System.out.println (”We are
in the third counstructor”);
x =ax;
y = ay;
z = az;
}
double get_x(){
return x;
}
double
get_y(){
return y;
}
double
get_z(){
return z;
}
}//end of
class Point3D definition (declaration).
class
Point3DOverloadConstructors {
public static void main(String input[]) {
//Declaring an object called p1 through
calling the counstructor
//that takes 1 parameter.
Point3D p1 = new Point3D(1.1);
//Printing the values of objects
variables
System.out.println(”p1:x=”+p1.get_x());
System.out.println(”p1:y=”+p1.get_y());
System.out.println(”p1:z=”+p1.get_z());
//Declaring an object called p2
through calling the counstructor
//that takes 2 parameter.
Point3D p2 = new Point3D(1.1,3.4);
//Printing
the values of objects variables
System.out.println(”p2:x=”+p2.get_x());
System.out.println(”p2:y=”+p2.get_y());
System.out.println(”p2:z=”+p2.get_z());
//Declaring an object called p3 through calling the counstructor
//that takes 3 parameter.
Point3D p3 = new Point3D(1.1,3.4,-2.8);
//Printing
the values of objects variables
System.out.println(”p3:x=”+p3.get_x());
System.out.println(”p3:y=”+p3.get_y());
System.out.println(”p3:z=”+p3.get_z());
}//end of main
}//end of class
Other references: http://java.sun.com/developer/onlineTraining/Programming/BasicJava2/oo.html#what