Tuesday, 14 April 2009

A simple OOPS concept

In this post I am going to discuss a simple OOPS concept. Consider the code snippet below.
class Base{}



class Derived extends Base
{
public void func()
{
System.out.println(“Inside the Derived class”);
}
}


public class Test
{
public static void main (String args[])
{
Base b = new Derived();
b.func();
}
}

What would happen if I try to compile and run the above code?
There are a few who might say that it would print “Insider the derived class”. The reason – Since at runtime the object that is created is a derived class object, it can call the method func(). But actually the code would not even compile. I agree that if the code would have compiled fine it would have called the func() method of the derived class but the problem is the compiler would not allow you to proceed because it does not see a func() method in the base class and thus b.func() would give a compile time error.

I agree a lot of you already feel like shouting ‘Come on codeguru… even a person who learnt OOPS from ‘OOPS for Dummies’ knows that’. But actually I have been interviewing candidates for a while and one common mistake a lot of candidates make is around this concept. Though it seems to be a very basic concept of OOPS, I have seen candidates with more than 2-3 years of experience failing to give a suitable reply. So I thought of including this in my blog. Sorry if it looks like that I have doubted your PQ(Programming Quotient). Remember we all started from the first step of the ladder and there are still a lot of them trying to do so.

No comments:

 
Technology