Access Modifiers


Access Modifiers

With the use of access modifiers we can restrict the scope or visibility of a package, class, constructor, methods, variables, or other data members. It is also known as access specifiers or visibility specifiers.

There are four types of modifiers as follows:

  • Default: When no access specifier is mentioned, it is assumed to be default.
    Scope is within the package. It doesn’t have specific keyword.
  • Public: Accessible inside and outside a class..
  • Private: Accessible within the same class. It ensures encapsulation in java..
  • Protected: Scope is within the package but can be accessed by other packages through inherited class. Therefore, it is mostly used in parent child relationships.

Default:

if we do not specify the access, it is public by default

Public:

the public access modifier is accessible everywhere. This is the default access modifier in java and hence it has the wide scope

Private:

strict accessibility within the class only

If we try to access the private member from outside the class, it will end up in a compilation error

Example:

Com.knowledge2life public class Main{ float income=40000; } class Website extends Main{ int bonus=10000; public static void main(String args[]){ Website p=new Website(); System.out.println("Website income is: "+p.income); System.out.println("Knowledge2life Bouns: "+p.bonus); } }

OUTPUT:

Website income is: 40000.0
Knowledge2life Bouns: 10000

Protected:

Only through inheritance, this access modifier is used. This can be applied to data member, constructor and method.