Thursday 2 February 2017

Components of Classes in Java ( PART - III )


                                                     
Components of Classes in Java ( PART - III )


 Access Specifiers

Access control is one of the most important attribute of Encapsulation. Through this we can control what parts of program can access the members of a class. 

Access specifiers modifies the declaration of members.There are  3 basic access specifiers : public , private , protected. Protected apples only when inheritance is involved.

When the members are modifies as public , then that member can be accessed by any other code. When a member of a class is specified as private, then that member can only be accessedd by other members of its class.

When no access specifier is used , then by default the member of a class is public within its own package , but cannot be accessed outside of its package.

Static keyword

When a member is declared as static , it can be accessed before any objects of its class are created and without reference to any object. Both member and method can be declared as static.

That is why main ( ) is declared as static as it must be called before any object exist. When object of class are declared , no copy of static variable is made and all the instances of the class share same static variable.


Final Keyword

When a variable is declared as final , it prevents its contents from being modified. So , the final variable must be intialized when it is declared.

Variable declared as final do not occupy memory on a per instance basis.So , a final variable is essentially a constant.

Final is also used to prevent method overriding. To disallow a method from being overridden , we specify final as a  modifier at the start of its declaration.The method declared as final canot be overridden.

Final is also used to prevent inheritance. when we precede the class declaration with the final keyword , we prevent it from being inherited.

Declaring a class final implicitly declares all of its method as final.


                                                                        By: Knowledge Bits

No comments:

Post a Comment

Video of the Day

Contact us

Name

Email *

Message *