$show=/label

Java Access Modifiers

SHARE:

Quick guide to Java Access Modifiers. Very Basic Java fundamentals of How to use Access Level Modifier in java on default, private, protected and public.

1. Overview


In this tutorial, We'll learn about Access Modifiers in Java. Java provides the 4 types of access modifiers for class, constructors, methods and instance variables.

These four access modifiers changes complete accessibility at various levels.

We will explore on each modifier as following.

A. default - No keyword is required
B. private
C. protected
D. public

Java Access Modifiers





This is a very basic in core java programming. If you understand this, you can crack any code in java application.



2. Default Access Modifier


If no keyword is specified at any level (class, constructors, methods and instance variables) then it is limited to its package. To apply default access modifier, we do not need to explicitly define on class or any.

A method without any access specifier then it is accessible with in the same package. Same rule is applicable for instance variable too.

See the below example at all levels of a class for default.

package com.blog.java.w3schools.default

classs Trade{

int tradeId = 12345;

int getTradeId(){
return tradeId;
}

If we try to access from outside of package then will get compile time error. Because, class Trade is not visible to outside packages.


In the above example, field tradeId, method getTradeId and class Trade are default because nothing is specified. So, all are limited to package.

Note: With respect to the Interfaces, Fields are by default public static final even though not specified anything and methods are public abstract.

3. private access modifier


private is not applicable to class and interface. Applicable to only methods, instance variables and constructors.

Once method or instance variable declared as private then it is accessible on within class. This is the highly restricted access modifier. No other has restricted like this.

class Studnet {

private int id studentId = 200;

public int getStudentId()
return studentId;
}
}

Take a look at above example where studentId is declared as private. That means there is no way to access directly with Studnet object as below.

Studnet stu = new Studnet();
int sid = stu.studentId;

This will though complete time error.

Accessing private variable is only using public getter method.

int stuId = stu.getStudentId();

If constructor is delcared as private then object is not allowed to created outside the class. This is important step in Singleton design pattern in java.

class MySingletonClass {
 private MySingletonClass(){
 
 } 
 // singleton code here
}

main() method should be public. If we make it private then JVM can not find the main method. We can not run this program.


4. protected access modifier


Comparatively higher access to default modifier but down to the public.

This can be used on variables, methods and constructors.

Protected variables, methods and constructors are accessed by all sub classes outside the package and all classes with in the same protected member's package.

We cannot apply protected to the class and interfaces. And also methods inside the interface can not be declared as protected.

SuperClass:

package com.blog.java.w3schools.same.pakage;

class SuperClass {
 protected void process() {
 
  // processing generic logic
 }
}

In the above examples, process() method is declared as protected in SuperClass class.

Now created a new sub class in different package.

Subclass:

package com.blog.java.w3schools.another.pakage;

class SubClass extends SuperClass{
 protected void processSubClass() {
 process();
  // processing sub class logic with generic logic from parent class.
 }
}


Observe the above subclass protected method process() is directly accessible in child class.

Note: Only protected methods, constructors and variables are accessible in child class outside package. default and private are not allowed to access outside the package.

5. public access modifier


public is the wider access modifier among all four in java. Anything is declared as public is allowed to access from anywhere from the application which is said as global access modifier.

This can be used on Class, Interface, Method, Constructor and instance variables. Once public is used at any level then we can access from any where such as within package, outside package or through inheritance.


But, We must have to import the package if accessing from outside package.

Example public class:

public class JavaGlobalClass{
 public boolean isGloble = true;
 
 public JavaGlobalClass(){
  // Creating instance.
 }
 
 public boolean getGlobalStatus(){
  
      return isGloble;
 }
}

In the above class, All are declared as public. In other words, visible to all others classes in the java world.

Public Example on interface:

public interface MyPublicInterface {
 public static final double PI = 3.14;
 public abstract Student getTopStudent();
}

6. Access Modifier's in Inheritance


consider the following class a subclass.

package com.blog.java.w3schools.another.pakage;

class SubClass extends SuperClass{
 protected void process() {
  // processing sub class releated implementation.
 }
}

Rules

  • If method is declared as public in super class then implementation in the child class implementation must be public.
  • If method is declared as protected in super class then implementation in the child class must be public or same level as protected.
  • If method is declared as default (no keyword) in super class then implementation in the child class must be public or protected or default. This child class must be in the same package because method is default in super class.
  • private methods are accessible to the class and not from outside of class. So, they do not participate in overriding.

7. Conclusion


In this article, We've seen What are Access Level Modifiers in Java. This is very basic and important topic in Java Fundamental programming concepts.

We have covered in detail on public, protected, default (no keyword required) and private modifiers with example code.

And also seen aspect of Inheritance in case of protected and public using child and super class relationship.



Java Access Modifiers Levels


Example code snippets shown in this article is available over GitHub.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,31,ArrayList,16,Arrays,2,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,4,Collections,20,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,5,Core Java,72,Corona India,1,Create,2,CSS,1,Date,2,Date Time API,3,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,2,Fast,1,Files,9,Float,1,Font,1,For examples,1,For loop examples,1,For Loop in Java,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HTML,2,HttpClient,2,Immutable,1,Inner for loops,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,28,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,java 5 For loop,1,Java 8,48,Java 9,1,Java Design Patterns,1,Java Files,1,Java for loop,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,Nested for loop,1,Nested for loop examples,1,New Features,1,Operations,1,Optional,4,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Softwares,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Stream,3,Streams,11,String,48,String Programs,8,String Revese,1,Swing,1,System,1,Tags,1,Threads,8,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Access Modifiers
Java Access Modifiers
Quick guide to Java Access Modifiers. Very Basic Java fundamentals of How to use Access Level Modifier in java on default, private, protected and public.
https://1.bp.blogspot.com/-pGyaQwU6TVo/XPUjALHAliI/AAAAAAAABoM/CI8QhRubBiQNS9PRQ4CaBlARVXnDVneNQCLcBGAs/s320/Java%2BAccess%2BModifiers.PNG
https://1.bp.blogspot.com/-pGyaQwU6TVo/XPUjALHAliI/AAAAAAAABoM/CI8QhRubBiQNS9PRQ4CaBlARVXnDVneNQCLcBGAs/s72-c/Java%2BAccess%2BModifiers.PNG
JavaProgramTo.com
https://www.javaprogramto.com/2019/06/java-access-modifiers.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/06/java-access-modifiers.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content