9th Day @ Noida: Access Modifier

Hi Readers!

I have learnt today about access modifier in Java.

Access Modifiers in Java
As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor, variable, method or data member. There are four types of access modifiers available in Java:

Default – No keyword required
Private
Protected
Public

access-modifiers-in-java

Default:
When no access modifier is specified for a class, method or data member – It is said to be having the default access modifier by default.

Private:
The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in which they are declared.
Any other class of the same package will not be able to access these members.
Top level Classes or interface cannot be declared as private because
private means “only visible within the enclosing class”.
protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, they apply only to nested classes and not on top level classes

protected:
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within the same package or subclasses in a different package.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method display in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B.

Comments

Popular posts from this blog

How to add Internet download manager extension in the Chrome browser

A Day in Noida: Learning Begins

Python Deciding factor