Polymorphism

Polymorphism is one of the object oriented concepts. Polymorphism means allowing objects with differing behavior that can be substitutable for one another.

You can take advantage of polymorphism by using Inheritance, either just Interface Inheritance or with Implementation Inheritance .

Method Overriding facilitates the differing behaviors in subtypes.

Without polymorphism …


if (...file...) {
    readFromFileStream(new FileInputStream("filename"));
} else if (...URL...) {
    readFromURLStream(new  URL(url).openStream());
} else if (...console...) {
    readFromConsoleStream(System.in);
} else if ...

  • Notice that the if else statements does similar things – to read from an input stream.

With polymorphism…

</pre>
<pre class="prettyprint"><span class="kwd">void</span><span class="pln"> readFromStream</span><span class="pun">(</span><b><span class="typ">InputStream</span><span class="pln"> stream</span></b><span class="pun">)</span> <span class="pun">{</span>
    <span class="pun">...</span><span class="pln">
    stream</span><span class="pun">.</span><b><span class="pln">read</span><span class="pun">()</span></b><span class="pun">;</span>
    <span class="pun">...</span>
<span class="pun">}</span></pre>
<pre>

InputStream is an abstract class, so any object of InputStream (extends InputStream) can be passed in the readFromStream(InputStream stream) regardless of the implementation of the read() function.

For example,

</pre>
<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="kwd">new</span> <span class="typ">FileInputStream</span><span class="pun">(</span><span class="str">"filename"</span><span class="pun">));</span></pre>
<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> URL</span><span class="pun">(</span><span class="str">"http://google.com"</span><span class="pun">).</span><span class="pln">openStream</span><span class="pun">());</span></pre>
<pre class="prettyprint"><span class="pln">readFromStream</span><span class="pun">(</span><span class="typ">System</span><span class="pun">.</span><span class="kwd">in</span><span class="pun">);</span></pre>
<pre>

FileInputStream extends InputStream, so it is legal to pass FileInputStream object to readFromStream() method.

In general, any object that extends InputStream can be passed to the readFromStream() method.

The type of the object you passed determines the what implementation of the behavior to be executed.

 

Inheritance

In this blog post, I’ll discuss about one of the concepts of Object Oriented Programming which is Inheritance. 

Inheritance is a way of deriving a class from another class. In the other words, a class can inherit the fields and methods from other class.

Code reuse

Inheritance is one way of achieving code reuse. Here’s why, when you want to create a new class and some functionality in it has already in another class, you can derive your class to the existing class. In doing this, you can reuse the fields and methods of the existing class without having to write the code again in your new class.

Subclass is the class that is derived from another class (also called extended class, derived class, or child class). This is more specific type of a class.

Superclass is the class from which a subclass is derived (also called parent class or base class).

inheritanceIn the picture above, Person class is the superclass of Student class and Employee class. On the other hand, Student class and Employee class are the subclasses of Person class. Student and Employee is a more specific type of a Person.

inheritance

Look at the class diagram above, notice that the Student class and Employee has no basic fields like firstName, lastName, lastName and age. It is because those fields are already inherited from the Person class. However, you can also declare those fields again with the same name in the subclass, thus, you are hiding the fields in the superclass (it can cause confusion and it is not recommended).

Not only the fields are inherited but also the methods (except for private methods) of the Person class. The methods eat() and sleep() of Person is inherited in the Student and Employee class.

You can add fields and methods to the subclass. In the case above, Student has a course and yearLevel fields and a study() method and Employee has salary and designation fields and a raiseSalary(int percent) method. By adding those fields and methods, you are extending the functionality of the class and that what makes the subclass more specific type.

You can change the behavior of the superclass by overriding it. Override a method by define a method with the same method signature, a method signature is the method name and the number and type of its parameters. Return types are not considered to be a part of the method signature.

If you liked this post, don’t forget to subscribe to this blog for more updates.

Encapsulation

In procedural programming language like C, data and behavior are mixed together in one file. The data can be accessed in any behavior. It means that some data can be changed by some behaviors that are not associated with that data. It leads to data corruption.

Reason for Data Insecurity in Procedural Programming

  • It is the global variables that leads to data insecurity
  • Global variables can be accessed in any functions in the program. So it means that the value of the global variables can be changed by the unrelated functions.
  • Whenever unrelated functions accessed that data, data corruption arises.

For example:


#include &lt;stdio.h&gt;

int result = 0;

int main() {
	result = sum(5, 5);
	printResult();
	return 0;
}

int sum(int firstNumber, int secondNumber) {
	return firstNumber + secondNumber;
}

int multiply(int firstNumber, int secondNumber) {
	return firstNumber * secondNumber;
}

void printResult() {
	printf(&quot;Result is %d&quot;, result);
}

void unrelatedFunction() { //assuming some unrelated behavior accesses the &quot;result&quot; variable
	result++;
}

Encapsulation?

Encapsulation is one of the core concepts in object oriented programming. Encapsulation is the binding of data with their corresponding behavior.

What is binding?

  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding we can restrict the availability of data to the unrelated functions
  • So that unrelated functions cannot access the data
  • Class is the base for encapsulation
public class Room {

	private long id;
	private String roomName;
	private String building;

	public String getRoomName() {
		return roomName;
	}

	public void setRoomName(String roomName) {
		this.roomName = roomName;
	}

	public String getBuilding() {
		return building;
	}

	public void setBuilding(String building) {
		this.building = building;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (int) (id ^ (id &gt;&gt;&gt; 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Room other = (Room) obj;
		if (id != other.id)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return roomName + &quot; &quot; + building;
	}
}

Abstraction

Abstraction is a way of dealing with things in a general way as much as possible, separate from specific details, implementations and instances.

According to wikipedia:

Abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time.

In this blog post, I will show to you simple ways how to achieve abstraction. Some of you implemented this concept but you’re unaware of it.

Abstraction via Functions

  • Processes can be grouped into functions
  • One function can call other function
  • You don’t have to understand each line, just what the function does
  • You can hide data to be accessible only within the function – local variables

double areaOfCircle(int radius) {

	return PI * radius * radius;

}

boolean isFirstBiggerThanSecond(int radius1, int radius2) {
	double area1, area2;
	area1 = areaOfCircle(radius1);
	area2 = areaOfCircle(radius2);
	return area1 &amp;gt; area2;
}

The areaOfCircle() method computes the area of the circle. The isFirstBiggerThanSecond() method compares the size of the circle if the first circle is bigger than the second one given the radius of the two. The isFirstBiggerThanSecond() called the areaOfCircle(). The one who writes the code of the isFirstBiggerThanSecond() method does not need to know how the implementation of the areaOfCircle() method. What he need to do is just to know what the areaOfCircle() does. The implementation on how to compute the area of the circle is separated and factored out so that who will ever use that method does not need to know how the computation is done, only what the function does.

Abstraction via Objects

Combining complex data types and the functions that operates on them give you objects.

public class Rectangle {
    private int length;
    private int width;

    public Rectangle (int length, int width) {
        this.length = length;
        this.width width;
    }

    public int area() {
        return length * width;
    }

    public boolean isBiggerThan(Rectangle other) {
        return this.area() > other.area();
    }   
}

Rectangle rect1 = new Rectangle(3, 4);
Rectangle rect2 = new Rectangle(5, 6);

if (rect1.isBiggerThan(rect2)) {
    buyPaint(rect2.area());
} else {
    buyPaint(rect1.area());
}

Objects are mini-programs, each with its own data and operations.

In Unix, we have a lot of little programs (grep, ls, cat…) that do just one thing. We can combine the little programs into bigger programs by having the output of one become the input of another.

OOP is the same. We make small, simple, specialized programs, and then make bigger programs by combining little programs (“Composition”).

“Think of an OO system as a bunch of intelligent animals (the objects) inside your machine, talking to each other by sending messages to one another.” – Allen Holub

OOP is a way to make programs easier to understand, by allowing bigger programs to be composed of smaller programs, and those smaller programs to be composed of even smaller programs, ad infinitum.

Those are only simple concepts that relates to abstraction. I found an interesting article which discusses abstraction using interface and abstract class in java.