java tutorial - Java modifiers | Access and class modifiers



Java modifiers

Learn Java - Java tutorial - Java modifiers - Java examples - Javaprograms

Modifiers are keywords that you add when initializing to change values. The Java language has a wide range of modifiers, the main ones are:

  • Access modifiers;
  • Modifiers for a class, method, variable, and thread that are not used for access.
java - java tutorial - java compiler - jdk - jre - java modifiers - learn java - java keywords - Java Tutorial for Complete Beginners - java basics concepts - java tutorial for beginners - java tutorial pdf - advanced java tutorial - java tutorial videos - java programming examples - core java tutorial

To use a modifier in Java, you need to include its keyword in the definition of a class, method, or variable. The modifier must be ahead of the rest of the statement, as shown in the following examples:


public class className {
   // ...
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main (String [] arguments) {
   // the body of the method
}
click below button to copy the code. By - java tutorial - team

Access Modifiers

In Java, it provides access modifiers to state access levels for classes, variables, methods as well as constructors. There are four accesses are given below:

  • Visible in the package (it is by default and the modifier is not required).
  • Visible only for the class (private).
  • Visible to all (public).
  • Visible to the package and all subclasses (protected).
java - java tutorial - java compiler - java bytecode - sample java program - learn java - java jdk - history of java - Java Tutorial for Complete Beginners - java basics concepts - java tutorial for beginners - java tutorial pdf - advanced java tutorial - java tutorial videos - java programming examples - core java tutorial

java - java tutorial - java compiler - jdk - jre - java modifiers - learn java - java jdk - history of java - Java Tutorial for Complete Beginners - java basics concepts - java tutorial for beginners - java tutorial pdf - advanced java tutorial - java tutorial videos - java programming examples - core java tutorial

The default access modifier is without a keyword

  • The default access modifier means that we explicitly do not declare the access modifier in Java for a class, field, method, etc.
  • A variable or method declared without an access control modifier is available for any other class in the same package.
  • The fields in the interface are implicitly public, static, final, and the methods in the interface are public by default.

Sample Code

Variables and methods can be declared in Java without any modifiers, as shown in the following example:

String version = "1.5.1";

boolean processOrder() {
   return true;
}
}
click below button to copy the code. By - java tutorial - team

The private access modifier

  • Modifier private – the methods, variables as well as constructors are declared as private in java, it can just be accessed inside the declared class itself.
  • This access modifier is mainly restrictive access level. The classes and interfaces cannot be private.
  • Variables declared private can be accessed outside the class if the public methods that they receive are present in the class (see the example and explanations below).
  • Using the private modifier in Java is the primary way to hide data.

Sample Code

The following class uses private access control:

public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}
click below button to copy the code. By - java tutorial - team
  • Here the format variable of the Logger class is private, so there is no way for other classes to get and set its value directly.
  • So, for this variable to be available for everything, we defined two public methods: getFormat (), that returns the value of format, and setFormat (String), which can be sets its value.

Public access modifier

  • Modifier public - the class, method, constructor, interface, and so on. declared as public can be accessed from any other class. Therefore, fields, methods, blocks declared within a public class can be accessed from any class belonging to the "universe" of Java.
  • However, if we try to access the public class in another package, then the public class must be imported.
  • Thanks to class inheritance, in Java all public methods and class variables are inherited by its subclasses.

Sample Code

The following function uses public access control:

public static void main(String[] arguments) {
   // ...
}
click below button to copy the code. By - java tutorial - team

The main () method must be public. Otherwise, it cannot be called using the java interpreter to start the class.

Access modifier protected

  • The protected modifier - variables, methods and constructors that are declared as protected in the superclass, can be accessed only for subclasses in another package or for any class in the protected class package.
  • The protected access modifier in Java cannot be applied to the class and interfaces. Methods and fields can be declared as protected, however methods and fields in the interface cannot be declared as protected.
  • Access protected gives the subclass the ability to use an auxiliary method or variable, preventing the unrelated class from trying to use them.

Sample Code

The following parent class uses protected access control so that its child class redefines the openSpeaker () method:


class AudioPlayer {
   protected boolean openSpeaker (Speaker sp) {
      // implementation details
   }
}

class StreamingAudioPlayer {
   boolean openSpeaker (Speaker sp) {
      // implementation details
   }
}
click below button to copy the code. By - java tutorial - team
  • In this case, if we define openSpeaker () as protected, then it will not be accessible from any other class, except AudioPlayer. If we define it as public, it will become available to everyone.
  • But our purpose is to expose this method just only to a subclass, that’s why we used the protected modifier.

Access control and inheritance rules

The given below rules in Java apply to inherited methods:

  • Methods declared as public in the superclass should also be public in all subclasses.
  • Methods declared as protected in superclass should either protected or public in subclasses; they cannot be private.
  • Methods declared as private for all are not inherited; hence there is no rule for them.
java - java tutorial - java compiler - jdk - jre - java modifiers - learn java - java jdk - history of java - Java Tutorial for Complete Beginners - java basics concepts - java tutorial for beginners - java tutorial pdf - advanced java tutorial - java tutorial videos - java programming examples - core java tutorial

Modifiers for a class, method, variable, and thread that are not used for access

Java provides a number of modifiers not for access, but for implementing much other functionality:

  • The static modifier is used to create methods and class variables;
  • The final modifier is used to complete the implementation of classes, methods, and variables;
  • The abstract modifier is used to create abstract classes as well as methods;
  • The modifiers synchronized and volatile are necessary in Java to flow.

The static modifier

  • A static modifier is used to create methods as well as class variables.

The static variables

  • The static keyword is required to create variables that will exist independently of any instances that already created for the class. Only one copy of the static variable in Java exists, regardless of the number of instances of the class.
  • Static variables are also called as class variables. In Java, local variables cannot be declared static.

The static methods

  • A static keyword is used to create methods which can exist independently of any instances created for the class.
  • In Java, static methods do not use any instance variables of any class object, that they are defined. The static methods take all the data from the parameters and some of these parameters are evaluated without reference to the variables.
  • Variables and methods of a class can be accessed using the class name, followed by the point and name of the variable or method.

Sample Code

The static modifier in Java is used to create class and variable methods, as shown in the following example:

public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount () {
      return numInstances;
   }

   private static void addInstance () {
      numInstances ++;
   }

   InstanceCounter () {
      InstanceCounter.addInstance ();
   }

   public static void main (String [] arguments) {
      System.out.println ("Starting with" +
      InstanceCounter.getCount () + "instance");
      for (int i = 0; i <500; ++ i) {
         new InstanceCounter ();
}
      System.out.println ("Created" +
      InstanceCounter.getCount () + "instances");
   }
}
click below button to copy the code. By - java tutorial - team

Output

Starting with 0 instance
500 copies created

The final modifier

The final modifier is used to complete the implementation of classes, methods, and variables.

Final Variables

  • The final variable can only be initialized once. A reference variable declared as final can never be assigned to designate another object.
  • However, the data inside the object can be changed. Thus, the state of the object can be changed, but not the reference.
  • With variables in Java, the final modifier is often used with static to make a constant a class variable.

Sample Code


public class Test {
  final int value = 10;
  // Below are examples of declaring constants:
  public static final int BOXWIDTH = 6;
  static final String TITLE = "Manager";
  
  public void changeValue () {
     value = 12; // get an error
  }
}
click below button to copy the code. By - java tutorial - team

Final methods

  • The final method cannot be overridden by any subclass. As mentioned earlier, in Java, the final modifier prevents the method from changing in a subclass.
  • The main intention to make the final method is that the content of the method should not be changed to the side.

Sample Code

The declaration of the method that uses the final modifier in the class declaration is shown in the following example:


public class Test {
    public final void changeName () {
       // the body of the method
    }
}
click below button to copy the code. By - java tutorial - team

Class final

The main purpose in Java of using a class declared as final is to prevent the class from being a subclass. If the class is marked as final, then no class can inherit any function from the final class.

Sample Code


public final class Test {
   // class body
}
click below button to copy the code. By - java tutorial - team

Modifier abstract

  • The abstract modifier is used to create abstract classes and methods.

Abstract class

  • The abstract class cannot instantiate. If a class is declared as abstract, then the only purpose for it is to be extended.
  • The class cannot be both abstract as well as final, because the final class cannot be extended. If the class contains abstract methods, then it should be declared as abstract or else, a compilation error will be generated.
  • An abstract class can contain both abstract methods, as well as ordinary methods.

Sample Code


abstract class Caravan {
   private double price;
   private String model;
   private String year;
   public abstract void goFast (); // abstract method
   public abstract void changeColor ();
}
click below button to copy the code. By - java tutorial - team

The abstract method

  • The abstract method is a method declared with any implementation. The body of the method (implementation) is provided by the subclass. Abstract methods can never be final or strict.
  • Any class that extends an abstract class has to implement all of the abstract methods of superclass if the subclass is not the abstract class.
  • If the class in Java contains one or more abstract methods, then the class should be declared as abstract. The abstract class is not necessary to contain abstract methods.
  • The abstract method should ends with a semicolon. Example: public abstract sample ();

Sample Code


public abstract class SuperClass {
    abstract void m (); // abstract method
}

class SubClass extends SuperClass {
     // implements the abstract method
      void m () {
.........
      }
}
click below button to copy the code. By - java tutorial - team

The synchronized modifier

The synchronized modifier is used in Java for threads.

  • The keyword synchronized is used to indicate that a method can only be accessed by one thread at a time. In Java, the synchronized modifier can be applied with any of the four access level modifiers.

Sample Code

public synchronized void showDetails(){
.......
}
click below button to copy the code. By - java tutorial - team

Transient modifier

  • The instance variable marked as transient points to the Java virtual machine (JVM) to skip a certain variable when serializing the object containing it.
  • This modifier is included in the statement, which creates a variable, the preceding class, or the data type of the variable.

Sample Code

public transient int limit = 55; // will not be saved
public int b; // will persist
click below button to copy the code. By - java tutorial - team

The volatile modifier

  • The volatile modifier is used in Java for threads.
  • A volatile modifier is used in Java, the JVM know which the variable access thread should always come together its own copy of the variable with the main copy in memory.
  • Access to the variable volatile synchronizes all cached copied variable in the RAM (Random Access Memory). The volatile can just be applied to the instance variables that are of type object otherwise private. A reference to a volatile object will be null.

Sample Code


public class MyRunnable implements Runnable {
    private volatile boolean active;
 
    public void run () {
        active = true;
        while (active) {// line 1
            // here is some code
        }
    }
    
    public void stop () {
        active = false; // line 2
    }
}
click below button to copy the code. By - java tutorial - team
  • Typically, run () is called in one thread (for the first time you use Runnable in Java), and stop () is called from another thread. If line 1 uses the cached value of active, the loop cannot stop until you set active false on line 2.
  • In the next lesson, we discuss the basic operators used in the Java language. This section will give you an overview of how you can use them during application development.

Related Searches to Java modifiers | Access and class modifiers