Access Modifiers (Lesson-27)

For now, you all remember this:

public static void main(String[] args)

When you got your first lesson, you were told that you will study these things in detail in the upcoming lessons. Now let's look at the parts of that statement from your first lesson:

You have learnt about all the components except Access Modifiers and static. We will learn about static in more detail in an upcoming lesson. For now we will concentrate on Access Modifiers.
Access modifiers are used to set a level of access for classes, methods and attributes. It defines that who can access a particular thing.
There are four types of access modifiers in java:
  • public
  • private
  • protected
  • default
We usually apply access modifiers to classes and attributes (as well as methods) in the classes.

Access Modifiers for classes:
There are two access modifiers for classes:
  • public: The class can be accessed by any other class
  • default: The class can be accessed by all the classes that are in the same package. The "default" is not a keyword. It means that it is applied when no access modifier is used. There is no need to type "default" when defining a class if you want to apply it.
Access Modifiers for attributes and methods:
All four access modifiers are applicable to attributes and methods.
  • public: Can be accessed from any other class.
  • private: Can be accessed only by the class in which it is present.
  • protected: Can be accessed by all the classes in the same package as well as sub classes. We will learn about subclasses and superclasses in an upcoming lesson.
  • default: Can be accessed by all the classes in the same package.

Post a Comment

0 Comments