Java Modifiers

Java modifiers are some specifc words that we put before : classes, attribute,  methode, or constructor to define a way of use.

There is 2 types of Java modifiers

  • Java Access Modifiers.
  • Java Non-Access Modifiers.

example of using :

public class book {

private int numberOfPages;

public static void main(String arg[]){

System.out.println("hello");

}

}

I) Java Access Modifiers.

There are modifiers used to set access levels for classes, variables, or methods and constructors. The four access levels are −

  • Without modifier (default access level): visibility to the package only.
  • “private” : Visible in the class only.
  • “public” : Visible any where inside a package or outside it.
  • “protected” :Visible in the package and all subclasses.

II)Java Non-Access Modifiers.

There are modifier that specify the way of managing classes object, attributes, or methods.

  • “static” :

-Make attribute myAttribute or method  myMethode() in a class MyClass simply accessible by MyClass.myAttribute and MyClass.myMethode(). without instantiate an object of MyClass to access them

Only in case of nested class (class MyClass inside an other class MyOuterClass) it make MyClass  accessible  simply by  MyOuterClass.MyClass without instantiate an object of MyOuterClass.

  • “final” : Make definition of class, attribute or method final (not changeable).

Final class cannot be derived, final method cannot be overridden, final attribute : basic attribute cannot been changed (like constant in C/C++) , for  attribute type object it’s the reference how will be constant not the value, like array in this  example:

public final int[] myArray={1,5,10};

...

myArray[0]=2 ;// the value of first item  can be changed but not the reference

  • “transient”: Make attribute myAttribute excluded when the object (instance of class having the attribute myAttribute ) is serialized. if the object is deserialized, the attribute will take the default value.
  • “synchronized” : Make method accessed by only one thread at a time.
  • “volatile” : Make attribute value allways read / write directly from / to the main memory , so there is no cach done by thread for the attribute value.
  • “abstract” :

-Make class impossible to instantiate, but still be possible to be drived.

-Make method declared without an implementation, so without braces :

 abstract void myMethod(int a); 

NB: if an abstract method myMethod() is part of a class MyClass,  the MyClass should be abstract

One thought on “Java Modifiers”

Leave a Reply

Your email address will not be published. Required fields are marked *