Showing posts with label Object Oriented. Show all posts
Showing posts with label Object Oriented. Show all posts

Monday, July 26, 2010

Runtime Polymorphism and Compile time Polymorphism is explained


Target audience: Beginners

Let’s look at some basics before get into details

What is polymorphism?
Polymorphism is one in many forms. That’s it. We can see lots of examples in real time. If you think about a Dog, A Dog is an Animal. A Dog can be a pet. So a Dog can be in
many forms. The Dog is Animal type and it can be another type of Pet.
Apart from types, behaviours can also take part of Polymorphism. For Example, Animals can swim. A Dog can swim, A Monkey also can swim. Dog and Monkey has their own way of swimming. Here, the swimming behavior is in many forms. A monkey can walk with two legs and also with four legs. Here, walking behaviour is in many forms. These are the examples for polymorphism in real world.

Let’s see how Polymorphism works in Java. Polymorphism allows you define a Super type and have multiple subtype implementations. There Are Two Types of Polymorphism in Java. One is compile time Polymorphism and it is sometimes referred as static Polymorphism and the other one is Runtime Polymorphism and it is sometimes referred as dynamic Polymorphism

Runtime Polymorphism
As we can have multiple subtype implementations for a super type, Java virtual machine determines the proper type to be invoked at the runtime. Method overriding is a runtime polymorphism. For example look at the following example. I have Worker interface(Super type) and have Teacher and Principal classes ( Subtypes) that implements the Worker interface .The Worker interface has a method doIt() and the subtypes implements that method.


// Worker class
interface Worker {
public void doIt();
}

// Teacher class
class Teacher implements Worker {
public void doIt() {
System.out.println("Teacher does the work");
}
}

//Principalclass
class Principal implements Worker {
public void doIt() {
System.out.println("Principal does the work");
}
}

Now I’m going to have another class which has a main method. The main method creates a List and adds a Principal instance and a Teacher instance to that list. Then it iterates through the list, refer the instances by their super type and calls the doit() method on the Super type reference

public class PolymorphismExample {

public static void main(String[] args) {
List workers = new ArrayList();

//Adding worker one
Worker worker1 = new Principal();
workers.add(worker1);

//Adding worker two
Worker worker2 = new Teacher();
workers.add(worker2);

for (Iterator iterator = workers.iterator(); iterator.hasNext();) {
Worker worker = (Worker) iterator.next();
worker.doIt();
}

}
}

If you run the PolymorphismExample class then the output will be

Principal does the work
Teacher does the work

If you see carefully, we cannot see which instance is called. We called doIt() method only on the Super type Worker but the JVM finds the proper type and called its implementation of doIt() method. This is Runtime Polymorphism. The JVM determines proper type only at runtime

Compile time Polymorphism
Method overloading is a compile time Polymorphism. As we can have multiple subtype implementations for a super type, the compiler determines which type to be invoked at the compile time. For example look at the following example. I’m going to change PolymorphismExample class to have some overloaded methods

public class PolymorphismExample {

public void doSomething(Worker worker) {
System.out.println("I'm a worker");
}

public void doSomething(Teacher teacher) {
System.out.println("I'm a Teacher");
}

public void doSomething(Principal principal) {
System.out.println("I'm a Principal");
}

public static void main(String[] args) {

PolymorphismExample example = new PolymorphismExample();
Worker principal = new Principal();
Worker teacher = new Teacher();

example.doSomething(principal);
example.doSomething(teacher);
}
}

You would expect the output as bellow, If you run the PolymorphismExample class

I'm a Principal
I'm a Teacher

WRONG, the actual output will be

I'm a worker
I'm a worker

Here the type is decided at compile time. Even though the objects are instances of Principal and Teacher, the reference is a Worker type. So the compiler picks the doSomething(Worker worker) method as it accepts the same type of reference type (Worker).
So keep it in mind when you use method overloading.

Tuesday, July 20, 2010

Instanceof operator kills Object Oriented Programming


Target audience: Beginners

Everybody knows about instanceof operator of Java. I just give a simple description about instanceof operator before get into details. The instanceof operator allows a user to check whether an object is an instance of a particular type.The type could be a class or an interface.

if (obj instanceof type) {
type new_name = (type) obj;
}

Here the obj is an instance of the type then, the condition will be true , else it will be false. This condition will also become false if obj is a null. So better to be careful while using it.

I personally feel that sometimes the instanceof operator is missused and it kind of kills the object oriented concept. Let me explain by taking a simple example similar to what we deal with everyday

Suppose we have abstact class Person and two other sub classes Student and Teacher

abstract class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

class Student extends Person {
void study() {
}
}

class Teacher extends Person {
void teach() {
}
}

Appart from the inherited methods, Student has a method study() and Teacher has a method teach(). Suppose if there is a situation that we have a list of mixed objects of Student and Teacher and we need to call their own methods. We might write a code similar to the following one.

List list = new ArrayList();
list.add(new Teacher());
list.add(new Student());

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Object object = (Object) iterator.next();
if (object instanceof Student) {
Student obj = (Student) object;
obj.study();
} else if (object instanceof Teacher) {
Teacher obj = (Teacher) object;
obj.teach();
}
}

This is the way we use the instanceof operator. We can get rid of this if we apply some Object oriented concept.What I'm going to do is, I’m going to change the Person,Student and Teacher classes a bit

abstract class Person {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

abstract void doYourWork();
}

class Student extends Person {

void study() {
}

void doYourWork() {
study();
}
}

class Teacher extends Person {
void teach() {
}

void doYourWork() {
teach();
}
}

I added a abstract method doYourWork() in Person class and let the sub classes Student and Teacher to implement it and call their own methods inside their implementation of doYourWork() method. Now i’m going to change the iterating part also.

List list = new ArrayList();
list.add(new Teacher());
list.add(new Student());

for (Iterator iterator = list.iterator(); iterator.hasNext();) {
Person object = (Person) iterator.next();
object.doYourWork();
}

Wow... the instance of operator is gone and code looks pretty too. I just applied a simple OO concept and got rid of the instanceof operator. This is why i mentioned “I personally feel that sometimes the instanceof operator is missused and it kind of kills the object oriented concept.”

Tuesday, June 29, 2010

Basics Of Class and Objects


Target audience: Beginners
When I learned java, i could not understand the contract between Class and objects. When i learned more and more,i could get the hang of it.I would like to share my understanding for the people who are beginning to learn about Java class and objects and specially for the people have confusion :)

Definition of the Class is “A template which describes the state(variables) and behavior(methods) of the object of its type.”

Imagine you are going to do business. you are going to manufacture Credit Cards for a client ( e.g: Bank). What will you do first before you start manufacturing? you will design a template or a prototype of a actual Credit Card. you will plan where the owners name should be printed. you will plan where the Credit Card number should be printed. The color ,size of the card and so on. Then you will get a list of user details from your client(E.g: Bank) to create the actual cards. Then you will manufacture thousands or millions of credit cards with actual data printed. You can imagine the ‘Class’ as ‘credit card template’ and the ‘Object’ as the actual credit card printed with user detail (may be with your name on it). The ‘state’ or ‘variables’ are the used detals( name, credit card number and all) That’s it. Classes are the templates of the objects.

//Class, is a template

public class Person {
private String name;
private int hight;

public void Person(String name, int hight) {
this.name = name;
this.hight = hight;
}

public void sayYourName() {
System.out.println(name);
}
}

//Objects, are the actual copies of class

Person me = new Person(“My Name”,185); 
Person you = new Person(“Your Name”,190);

When Java find the “new” key word, then it creates a object or instance(actual copy )of the class and keep it in it memory

Hope it clears your confusion and helps you to understand