Skip to main content

Member modifiers


Member modifiers:
Public members:
If a member declared as the public then we can access that member from anywhere“but the corresponding class must be visible” hence before checking member visibility we have to check class visibility.
Example:
Program 1:
        package pack1;
        class A
            {
               public void methodOne()
                  {
                      System.out.println("a class method");
                   }
        }
D:\Java>javac -d . A.java
Program 2:
         package pack2;
         import pack1.A;
         class B
            {
                public static void main(String args[])
                     {
                            A a=new A();
                            a.methodOne();
                      }
             }
Output:
Compile time error.
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside package import pack1.A;
In the above program even though the methadone() method is public we can’t access class B because the corresponding class A is not public that is both classes and methods are public then only we can access.
Default member:
If a member declared as the default then we can access that member only within the current package hence default member is also known as package level access.
Example 1:
Program 1:
       package pack1;
       class A
               {
                   void methodOne()
                       {
                             System.out.println("methodOne is executed");
                       }
                }
Program 2:
          package pack1;
          import pack1.A;
           class B
                {
                     public static void main(String args[])
                       {
                                A a=new A();
                                a.methodOne();
                       }
                }
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
Example 2:
Program 1:
          package pack1;
             class A
                 {
                      void methodOne()
                           {
                                 System.out.println("methodOne is executed");
                            }
                 }
Program 2:
             package pack2;
             import pack1.A;
             class B
                 {
                     public static void main(String args[])
                            {
                                  A a=new A();
                                  a.methodOne();
                            }
                }
Output:
Compile time error.
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
B.java:2: pack1.A is not public in pack1; cannot be accessed from outside package import pack1.A;
Private members:
If a member declared as the private then we can access that member only within the current class.
Private methods are not visible in child classes whereas abstract methods should be visible in child classes to provide implementation hence private, the abstract combination is illegal for methods.
Protected members:
If a member declared as the protected then we can access that member within the current package anywhere but outside packages only in child classes.
Protected=default+kids.
We can access protected members within the current package anywhere either by child reference or by parent reference but from the outside package, we can access protected members only in child classes and should be by child reference only that is we can’t use parent reference to call protected members from outside language.
Example:
Program 1:
           package pack1;
          public class A
               {
                     protected void methodOne()
                         {
                              System.out.println("methodOne is executed");
                          }
              }
Program 2:
        package pack1;
        class B extends A
             {
                   public static void main(String args[])
                          {
                                  A a=new A();
                                  a.methodOne();
                                  B b=new B();
                                  b.methodOne();
                                 A a1=new B();
                                 a1.methodOne();
                         }
            }
Output:
D:\Java>javac -d . A.java
D:\Java>javac -d . B.java
D:\Java>java pack1.B
methodOne is executed
methodOne is executed
methodOne is executed
Example 2: 
Compression of private, default, protected and public:
The least accessible modifier is private.
The most accessible modifier is public.
Private<default<protected<public.
Recommended modifier for variables is private where as recommended modifier for methods are public.
Final variables:
Final instance variables:
If the value of a variable is varied from object to object such type of variables is called instance variables.
For every object, a separate copy of instance variables will be created.
DIAGRAM:
For the instance variables it is not required to perform initialization explicitly JVM will always provide default values.
Example:
         class Test
            {
                  int i;
                  public static void main(String args[])
                        {
                              Test t=new Test();
                              System.out.println(t.i);
                        }
           }
Output:
D:\Java>javac Test.java
D:\Java>java Test 
0
If the instance variable declared as the final compulsory we should perform initialization whether we are using or not otherwise we will get compile time error.
Example:
            Program 1:
                  class Test
                          {
                                  int i;
                           }
Output:
D:\Java>javac Test.java
D:\Java>
Program 2:
            class Test
                 {
                      final int i;
                 }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:1: variable I might not have been initialized
class Test
Rule:
• For the final instance variables, we should perform initialization before the constructor completion. That is the following are various possible places for this.
1) At the time of declaration:
Example:
          class Test
               {
                    final int i=10;
               }
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside instance block:
Example:
     class Test 
         { 
            final int i;
                 {
                      i=10;
                 }
          }
Output:
D:\Java>javac Test.java
D:\Java>
3) Inside constructor:
Example:
         class Test
              {
                  final int i;
                  Test()
                      {
                            i=10;
                       }
              }
Output:
D:\Java>javac Test.java
D:\Java>
If we are performing initialization anywhere else we will get compile time error.
Example:
         class Test
              {
                   final int i;
                   public void methodOne()
                      {
                           i=10;
                       }
              }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to the final variable i.
i=10; 
Final static variables:
If the value of a variable is not varied from object to object such type of variables is not recommended to declare as the instance variables. We have to declare those variables at the class level by using a static modifier.
For the static variables it is not required to perform initialization explicitly JVM will always provide default values. 
Example:
        class Test
             {
                   static int i;
                   public static void main(String args[])
                      {
                          System.out.println("value of i is :"+i);
                      }
             }
Output: 
D:\Java>javac Test.java
D:\Java>java Test
Value of i is: 0
• If the static variable declared as final then compulsory we should perform initialization explicitly whether we are using or not otherwise we will get compile-time error.
Example:
Rule:
For the final static variables, we should perform initialization before class loading completion otherwise we will get a compile-time error. That is the following is possible
places.
1) At the time of declaration:
Example:
         class Test
             {
                    final static int i=10;
              }
Output:
D:\Java>javac Test.java
D:\Java>
2) Inside static block:
Example:
      class Test
            {
               final static int i; 
               static
                  {
                       i=10;
                   }
             }
Output:
Compile successfully.
• If we are performing initialization anywhere else we will get compile-time error.
Example:
          class Test
              {
                      final static int i;
                      public static void main(String args[])
                         {
                                i=10;
                          }
              }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: cannot assign a value to the final variable i
i=10; 
Final local variables:
To meet the temporary requirement of the programmer sometimes we can declare the variable inside a method or block or constructor such type of variables is called local variables.
For the local variables, JVM won’t provide any default value compulsory we should perform initialization explicitly before using that variable.
Example:
          class Test
              {
                       public static void main(String args[])
                           {
                                int i;
                                System.out.println("hello");
                            }
               }
Output:
D:\Java>javac Test.java
D:\Java>java Test
Hello
Example:
         class Test
              {
                   public static void main(String args[])
                       {
                            int i;
                            System.out.println(i);
                        }
               }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: variable I might not have been initialized
System.out.println(i);
Even though local variables declared as the final before using only we should perform initialization.
Example:
            class Test
                  {
                       public static void main(String args[])
                           {
                                    final int i;
                                    System.out.println("hello");
                            }
                   }
Output:
D:\Java>javac Test.java
D:\Java>java Test
hello
Note: The only applicable modifier for local variables is final if we are using any other modifier we will get compile time error.
Example:
Output:
Compile-time error. 
D:\Java>javac Test.java
Test.java:5: illegal start of expression
private int x=10;
Formal parameters:
The formal parameters of a method simply access local variables of that method hence it is possible to declare formal parameters as final.
If we declare formal parameters as final then we can’t change its value within the method.
Example: 
Static modifier:
Static is the modifier applicable for methods, variables, and blocks.
We can’t declare a class with static but inner classes can be declared as the static.
In the case of instance variables for every object, a separate copy will be created but in the case of static variables, a single copy will be created at the class level and shared by all objects of that class. 
Example: 
Output:
D:\Java>javac Test.java
D:\Java>java Test
888.....20
Instance variables can be accessed only from instance area directly and we can’t access from the static area directly.
• But static variables can be accessed from both instance and static areas directly.
1) Int x=10;
2) Static int x=10;
3) Public void methodOne(){
         System.out.println(x);
     }
4) Public static void methodOne(){
        System.out.println(x);
    }
Which are the following declarations are allowed within the same class simultaneously?
a) 1 and 3
Example:
         class Test
             {
                   int x=10;
                   public void methodOne()
                      {
                          System.out.println(x);
                       }
              }
Output:
Compile successfully.
b) 1 and 4
Example:
           class Test
                {
                        int x=10;
                        public static void methodOne()
                              {
                                     System.out.println(x);
                              }
                   }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:5: non-static variable x cannot be referenced from a static context
System.out.println(x);
c) 2 and 3
Example:
class Test
          {
                 static int x=10;
                 public void methodOne()
                       {
                            System.out.println(x);
                        }
            }
Output:
Compile successfully.
d) 2 and 4
Example:
           class Test
               {
                    static int x=10;
                    public static void methodOne()
                        {
                              System.out.println(x);
                         }
                  }
Output:
Compile successfully.
e) 1 and 2
Example:
              class Test
                 {
                        int x=10;
                        static int x=10;
                  }
Output:
Compile time error.
D:\Java>javac Test.java
Test.java:4: x is already defined in Test
static int x=10;
f) 3 and 4
Example:
           class Test
                  {
                        public void methodOne()
                            {
                                   System.out.println(x);
                             }
                       public static void methodOne()
                             {
                                     System.out.println(x);
                              }
                 }
Output:
Compile time error.
D:\Java>javac Test.java  
Test.java:5: methodOne() is already defined in Test
public static void methodOne(){
Overloading concept is applicable for static method including main method also.
Example:
Inheritance concept is applicable for static methods including the main() method hence while executing child class, if the child doesn’t contain the main() method then the parent class main method will be executed. 
Example:
             class Parent
                 {
                      public static void main(String args[])
                          {
                          System.out.println("parent main() method called");
                          }
                   }
            class child extends Parent{
              }
Output:
Example:
Output:
It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding.
• For static methods, the compulsory implementation should be available whereas abstract methods implementation should be available hence abstract static combination is illegal for methods.
Native modifier:
• Native is a modifier applicable only for methods but not for variables and classes.
• The methods which are implemented in non-java are called native methods or foreign methods.
The main objectives of the native keyword are:
• To improve the performance of the system.
• To use already existing legacy non-java code.
To use the native keyword:
Pseudocode:
For native methods implementation is already available and we are not responsible for providing implementation hence native method declaration should compulsory ends with a semicolon.
Public native void methodOne()----invalid
Public native void methodOne();---valid 
For native methods implementation is already available whereas for abstract methods implementation should not be available child class is responsible to provide that, hence the abstract native combination is illegal for methods.
We can’t declare a native method as strictfp because there is no guaranty whether the old language supports the IEEE754 standard or not. That is the native strictfp combination is illegal for methods.
For native methods inheritance, overriding and overloading concepts are applicable.
The main disadvantage of a native keyword is the usage of native keyword in java breaks the platform-independent nature of java language.
Synchronized:
Synchronized is the modifier applicable for methods and blocks but not for variables and classes.
If a method or block declared with a synchronized keyword then at a time only one thread is allowed to execute that method or block on the given object.
The main advantage of a synchronized keyword is we can resolve data inconsistency problems, but the main disadvantage is it increases the waiting time of the threads and effects the performance of the system. Hence if there is no specific requirement never recommended using synchronized keyword.
Transient modifier:
Transient is the modifier applicable only for variables but not for methods and classes.
At the time of serialization if we don’t want to serialize the value of a particular variable to meet the security constraints then we should declare that variable with a transient modifier.
At the time of serialization, JVM ignores the original value of the transient variable and save default value that is transient means “not to serialize”.
Static variables are not part of the object state hence serialization concept is not applicable for static variables duo to this declaring a static variable as transient there is no use.
Final variables will be participated in serialization directly by their values due to this declaring a final variable as transient there is no impact.
Volatile modifier:
Volatile is the modifier applicable only for variables but not for classes and methods.
If the value of the variable keeps on changing such types of variables we have to declare with a volatile modifier.
If a variable declared as volatile then for every thread a separate local copy will be created by the JVM, all intermediate modifications performed by the thread will take place in the local copy instead of the master copy. 
Once the value got finalized before terminating the thread that the final value will be updated in the master copy.
The main advantage of a volatile modifier is we can resolve data inconsistency problems, but creating and maintaining a separate copy for every thread increases the complexity of the programming and effects the performance of the system. Hence if there is no specific requirement never recommended to use a volatile modifier and it’s almost outdated.
Volatile means the value keeps on changing whereas final means the value never changes hence final volatile combination is illegal for variables. 
Summary of modifier:
The modifiers which are applicable for inner classes but not for outer classes are private, protected, static.
The modifiers are applicable only for methods native.
The modifiers are applicable only for variables transient and volatile.
The modifiers which are applicable for constructor public, private, protected, default.
The only applicable modifier for local variables is the final.


Comments

Popular posts from this blog

Core Java

Content 1 - Language fundamental   Identifier Reserved words Data types Literals Arrays Types of variables Var arg method Main method Java coding standards 2 -  Declaration and Access Modifiers Java source file structure Class modifiers Member modifiers Interfaces 3 - Exception Handling Introduction Runtime stack mechanism Default exception handling in java Exception hierarchy Customized exception handling by try-catch  Control flow in try-catch Methods to print exception information Try with multiple catch blocks Finally Difference between final, finally, finalize Control flow in try-catch-finally Control flow in nested try-catch-finally Various possible combinations of try-catch-finally throw keyword throws keyword Exception handling keywords summary Various possible compile-time errors in exception handling Customized exceptions Top-10 exceptions  4 - String Concept of String Immutable String String Comparison String Conca