Tuesday 30 October 2012

Access specifier in Java : A love story

Access specifier in java is an important topic since it controls the flow of application. Also we can't write a simple application without any one of the four access specifier. So now you understand the importance of access specifiers.

So let's look into different access specifiers in java. We have public, protected, default and private access specifiers in java. Where exactly we can use this in a java application?

Public - No doubt in this, if we need to make instance or method accessible to entire outside world make it as public.

Private - This is also simple, If we want to make instance or method accessible only to the containing class make it as private.

Protected - This is somewhat confusing, where exactly we have to use it? If we need to share some instance or method to all the child classes with in the same package or different package mark it as protected.

Default -Hmm...So what is this?  If we need to share some instance or method to all the child classes with in the same package mark it as default. Here if any try to access default members from outside the package will result in compilation error.

Order of accessibility

private<default<protected<public

So here is a story to remember this stuff:

Suppose you are belongs to a big family. Also you have a secret love (We can say it as an instance variable).

If you want to keep your love as public makes it as a public love so that everyone knows about it.

If you want to keep your love as a secret for yourself, make it as a private love so that only you know about it.

If you want to keep your love with in your close family mark is as a default love (Note: here close family means any family which has a close relationship with your family....in java term it is subclass under the same package).

If you want to keep your love with in your big family mark is as a protected love (Note: here big family means any family which has a relationship with your family and located anywhere....in java term subclass under different package).

Hope this Helps!!!

1 comment:

  1. A good example with good explanation...

    Now i'll never forget this concept...

    Thank you

    ReplyDelete