CodesJava

Easy learning with example program codes

Access modifier in java


Access modifiers:

Access modifiers are keywords used for defining accessibility of classes, methods and data members.

Types of access modifier.

  1. Private.
  2. Default
  3. Protected
  4. Public

Private:

Data members, methods and constructors that are declared with private access modifier can be accessed into that class only.

Example:

PrivateAccessModifier.java

/**
 * This program is used to show that private members
 * of a class can be accessed in that class only
 * @author CodesJava
 */
class Student {
      //private members of the class
      private int rollNo = 5;
 
      private void showRollNo(){
              //rollNo which a private data member is
              //accessible in that class.
              System.out.println("RollNo = " + rollNo);
      }
}
 
public class PrivateAccessModifier {
       public static void main(String args[]){
              //creating Student class object
              Student obj = new Student();
 
              //compile time error because private members
              //of a class can be accessed in that class only.
              System.out.println(obj.rollNo);
 
              obj.showRollNo();
       }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problems:
The field Student.rollNo is not visible
The method showRollNo() from the type Student is not visible
at com.codesjava.business.PrivateAccessModifier.main
(PrivateAccessModifier.java:24)

Download this example.

Note: A class can have a private constructor but we cannot create an instance of that class from outside the class.

PrivateConstructor.java

/**
 * This program is used to show that we cannot create an instance
 * of that class from outside the class if constructor is private.
 * @author CodesJava
 */
class Student {
      //private constructor of the class
      private Student(){                               
 
      }
 
      public void show(){
             System.out.println("Hello javawithease.com");
      }
}
 
public class PrivateConstructor {
       public static void main(String args[]){
               //compile time error in creating Student class object
               //because of private constructor.
               Student obj = new Student();
       }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The constructor Student() is not visible
at com.codesjava.business.PrivateConstructor.main
(PrivateConstructor.java:22)

Download this example.

Note: Classes and interfaces can’t be private except nested classes.

Default:

Classes, data members, methods and constructors that are not declared with any access modifier are treated as default. They can be accessed into all classes within the same package only.

Example 1:

DefaultAccessModifier1.java

/**
 * This program is used to show that members of the class
 * of a class can be accessed in the package level only.
 * @author CodesJava
 */
class Student {
      //private members of the class
      int rollNo = 5;
 
      void showRollNo(){
           System.out.println("RollNo = " + rollNo);
      }
}
 
public class DefaultAccessModifier1 {
        public static void main(String args[]){
               //creating Student class object
               Student obj = new Student();
 
               //No compile time error because members of the class
               //of a class can be accessed in that package but can't be
               //accessed outside the package.
               System.out.println(obj.rollNo);
               obj.showRollNo();
         }
}

Output:

5
RollNo = 5

Download this example.

Example 2:

Display.java

package com.codesjava.display;
/**
 * This class is used to print a line.
 * @author CodesJava
 */
class Display {
      void display(){
           System.out.println("Hello javawithease.com");
      }
}

Test.java

package com.codesjava.test;
import com.codesjava.display.*;
/**
 * This program is used to show that default members of the class
 * are not accessible from outside the package.
 * @author CodesJava
 */
public class Test {
        public static void main(String args[]){
               //compile time error because default members of the class
               //are not accessible from outside the package.
               Display obj = new Display();
               obj.display();
       }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problems:
The type Display is not visible
The type Display is not visible
The type Display is not visible
at com.codesjava.test.Test.main(Test.java:13)

Download this example.

Protected:

Data members, methods and constructors that are declared with protected access modifier can be accessed into all classes within the same package and only in subclasses outside the package.

Example 1:

Display.java

package com.codesjava.display;
/**
 * This class is used to print a line.
 * @author CodesJava
 */
public class Display {
       protected void display(){
                 System.out.println("Hello codesjava.com");
        }
}

Test.java

package com.codesjava.display;
package com.codesjava.test;
 
import com.codesjava.display.*;
/**
 * This program is used to show that protected members of the
 * class are accessible from outside the package in subclasses.
 * @author CodesJava
 */
public class Test extends Display{
        public static void main(String args[]){
               Test obj = new Test();
 
               //No compile time error because protected members
               //of the class are accessible from outside the
               //package in subclasses.
               obj.display();
         }
}

Output:

Hello codesjava.com

Download this example.

Example 2:

Display.java

package com.codesjava.display;
/**
 * This class is used to print a line.
 * @author CodesJava
 */
public class Display {
       protected void display(){
                 System.out.println("Hello codesjava.com");
       }
}

Test.java

package com.codesjava.test;
 
import com.codesjava.display.*;
/**
 * This program is used to show that protected members of the class
 * are not accessible from outside the package in non-subclasses.
 * @author CodesJava
 */
public class Test {
       public static void main(String args[]){
              Display obj = new Display();
              //compile time error because protected members
              //of the class are not accessible from outside
              //the package in non-subclasses.
              obj.display();
        }
}

Output:

Exception in thread "main" java.lang.Error: 
Unresolved compilation problem:
The method display() from the type Display is not visible
at com.codesjava.test.Test.main(Test.java:15)

Download this example.

Note: Classes and interfaces can’t be protected except nested classes.

 Public:

Classes, data members, methods and constructors that are declared with public access modifier can be accessed everywhere.

Example:

Display.java

package com.codesjava.display;
/**
 * This class is used to print a line.
 * @author CodesJava
 */
public class Display {
       public void display(){
              System.out.println("Hello codesjava.com");
       }
}

Test.java

package com.codesjava.test;
 
import com.codesjava.display.*;
/**
 * This program is used to show that public members of the class
 * are accessible everywhere.
 * @author CodesJava
 */
public class Test {
       public static void main(String args[]){
              Display obj = new Display();
              //public members of the class accessible everywhere.
              obj.display();
       }
}

Output:

Hello codesjava.com

Download this example.
 
Next Topic: Static import in java with example.
Previous Topic: Package in java with example.

Related Topics:

Package in java with example.
Access modifier in java with example.
Static import in java with example.
Package class in java with example.
this in java with example.
Instance initialize/ Anonymous block in java with example.
super in java with example.
Static in java with example.
final in java with example.

 

Core Java Tutorial

Programming language overview.
Overview of Java.
Java features
JVM architecture details.
JVM, JRE and JDK.
Java Coding Guidelines.
Some important definitions.
Variable and data types.
Hello world java program.
Core java examples programs.
Important Java Programs.
How to set permanent path in java?
OOPs Basics.
Object and Class in Java.
OOPs Principles/Concepts.
Abstraction in java.
Encapsulation in java.
Polymorphism in java.
Method overloading in java.
Method overriding in java.
Dynamic method dispatch.
Runtime polymorphism.
Association in java.
Inheritance in java.
Aggregation in java.
Command line arguments in java.
Command line argument program in eclipse.
Read input from command line using Scanner.
Java array programs
Java star pattern programs
Java number pattern programs
final in java.
Abstract class in java.
Interface in java.
Custom marker Interface in java.
Constructor in java.
Package in java.
Access modifier in java.
Static import in java.
Package class in java.
this in java.
Instance initialize block.
Anonymous block.
super in java.
Static in java.
final in java.
Java cloning deep and shallow
Shallow vs Clone copy
String handling in java.
String handling programs.
StringBuffer in java.
StringBuilder in java.
Exception Handling Tutorial.
Multithreading Tutoial.
Java input output stream tutorial.
Collections framework in java tutorial.
Collections framework programs.
Java Random class
Java annotations.
Java design principles.
Java 7 features
Java 8 features
Java networking tutorial
Java Reflection tutorial


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap