$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,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,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,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,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://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieBegTKjFkKOX8VP23MM-l2aiLT8VBAGUIKYAOqyy7BvML2mfHLgevZhKNb6Qq5nlg_pc4Ixs_6AuX0m0u5w92Ft07nlQOue5cOv-Q_4l0auqlauTotp63UkHTP9mmnCLRh5fC2BS1T4o/s320/Java+Access+Modifiers.PNG
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEieBegTKjFkKOX8VP23MM-l2aiLT8VBAGUIKYAOqyy7BvML2mfHLgevZhKNb6Qq5nlg_pc4Ixs_6AuX0m0u5w92Ft07nlQOue5cOv-Q_4l0auqlauTotp63UkHTP9mmnCLRh5fC2BS1T4o/s72-c/Java+Access+Modifiers.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