Full width home advertisement

Post Page Advertisement [Top]

Java Modifiers Tree

What is Java Modifier?

Java Modifier is a keyword used for changing the behavior of variable or class in term of its usage.
Java Modifier is categorized in two parts:-

  1. Access Modifier
  2. Non Access Modifier 

How can we use a modifier?

Simple usage of modifier:

modifier variableName;

where modifier is a keyword i.e. public, private, protected, static, final etc...


What is Java Access Modifier?

Java Access Modifier is like a security key which gives different access to classes, variables, methods or constructor .  In simple word, it controls the access level and it use for security reason.
The four Java Access Modifier are:
  1. default :-> It gives access to package (no need to write it).
  2. public :-> Give access to the world.
  3. private :-> Give access to the class only.
  4. protected :-> Give access to package and all sub classes.
Example:


//This class can be used by the world.
public class Test{
   private int myInt; //this variable only access by class Test.
   public String myString; //this variable access by everyone.
   protected int count; //this variable can access in class and sub class.

   private void myMethod(){
    
   }
}


What is Java Non Access Modifier?

Java Non Access Modifier provide various functionality and they are as follows:
  1. static :-> this modifier allows direct access to method and variable without creating an object for its class.
  2. final :-> this modifier affect class, method and variable too in following ways:
    1. A class cannot be subclassed by using final modifier.
    2. A method cannot be override with its sub class.
    3. A variable cannot change its value one initialized.
  3. abstract :-> it use for creating abstract class or method. It means if a class is abstract then it can't be use as a object. It only work as a parent class and it's subclass must have to complete its abstract methods.
    Example:

    abstract class A{
        ......
        ......
        public abstract void myMethod();
    }

    class B extends A{
        ......
        ......
        @Override    public void myMethod(){
           .....
           .....
        }
    }
  4. synchronized :->this modifier used in thread, so we can discuss in Thread tutorial.
  5. volatile :-> this modifier also used in thread.
Some important information: 
  1. We can use  1 Access Modifier with  1 or more Non-Access Modifier for same variable/class/method.
  2. We cannot use abstract and final same time.
  3. We cannot use private with abstract.

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib