Diwali Deal : Flat 20% off + 2 free self-paced courses + Free Ebook + $200 Voucher  - SCHEDULE CALL

- Java Blogs -

Java Access Modifiers - Public, Private, Protected & Default

Java, developed by Sun Microsystems and released in 1995, is considered as a high-level programming language. James Gosling first used it. It is supported by many platforms like Windows, Mac OS, and many other versions of UNIX. Java SE 8 is the newest release of the Java Standard Edition. Many platforms were being taken care of by the multiple configurations of Java, which led to its rising popularity. E.g., Enterprise Applications were handled by J2EE, and Mobile Applications were handled by the J2ME. The underlying principle of Java is that it is Write Once, Run Anywhere type of language which comes loaded with many features:

  • Object-Based: Everything is considered as an Object in Java, which can be easily extended when it is based on an Object model.
  • Platform Independent: Java, unlike other programming languages, is compiled into a platform which is independent of byte code. The byte code is spread over the web and is interpreted by the JVM on any platform on which it is run.
  • Simplicity: Java is generally considered as easy to master, and if you can understand the basic concepts of OOP Java, it becomes easier.
  • Secure: The secure feature of Java allows it for developing virus-free and tamper-free systems. All kinds of authentication are based on public-key encryption.
  • Architecture-neutral: An architecture-neutral object file format is generated by the Java Compiler, which can be executed on many processors which have Java runtime system.
  • Robust: Java is instrumental in eliminating various error-prone situations which focus primarily on the compile-time error checking and runtime checking.
  • Multithreaded: It is the multithreaded feature of Java, which makes it possible for it to write various programs and also perform multiple tasks in one go.
  • High Performance: Java can give high performance due to its just-in-time compilers.
  • Distributed: Java is typically designed for a distributed internet environment.

Introduction of Access Modifiers in Java

Access Modifiers are the keywords which are used in object-oriented languages which have a set of classes, methods, and other members. They comprise a particular part of the programming language syntax which is instrumental in the facilitation of encapsulation of the components.

Java has many access modifiers for setting access levels for classes, variables, methods, and constructors. They basically point to which classes can access a particular class and its fields, methods, and constructors. They are generally, thus allotted to a class, in particular, its various constructors, fields, and methods. They are also called the Java access specifiers.  They come in four different levels:

  • Default: these are just visible to the package. No modifiers are needed.
  • Private: these are just visible to the class.
  • Public: these are visible to the world.
  • Protected: these are visible to the package and all subclasses.

When a specific access modifier is assigned to a particular class, constructor, field or even method, it is known as “marking” that class, constructor, field, or even the method.

1). Private Access Modifier

If any method or a variable is designated as private, i.e. a private access modifier is assigned to it, then only the code which is inside the same class can actually access the variable, or call that method. Code which lies inside any subclass cannot access the variable, not even the code which belongs to an external class. Classes are never labeled or marked with a private access modifier. Marking any class with a private access modifier will mean that any other class can not access it. In other words, it means that it cannot use any class at all. Thus, the private access modifier cannot really be allowed for classes.


public class Clock {

private long time = 0;

}

In the above picture, it is evident that the member variable has been marked as private which implies that the member variable time inside the Clock class cannot be accessed from code outside the Clock class.

Read: What Is The Process To Run A Java Program In CMD?

2). Accessing the private Fields through Accessor Methods

Various fields are declared private for controlling access to them from the outside world. In many cases, fields are particularly private, i.e., they can only be used internally in the class. In other instances, the fields can, however, be accessed by the accessor methods like getters and setters. E.g.


public class Clock {

private long time = 0;

public long getTime() {

return this.time;

}

Public void setTime(long theTime) {

this.time = theTime;

}

}

The above example states two methods, getTime () and setTime() which can access the member variable time. Both the methods are declared as public, i.e. they can be called from code anywhere in the application.

3). Private Constructors

If the private Java access modifier is assigned to any private constructor in a class, it typically means that the constructor cannot be called from just anywhere outside the class. However, the private constructor can still get called from other constructors, or even from the static methods which are in the same class as shown below:


public class Clock {

private long time = 0;

public long getTime() {

this.time = time;

}

public Clock(long time, long timeoffset){

this(time);

this.time += timeoffset;

}

Public Static Clock newClock(){

return new Clock(system.currentTimemillis());

}

}

Introduction of Non-Access Modifiers in Java

In this version, the Clock class has a private constructor and a public constructor. The former is called from the public constructor while the latter is called from the static method new clock(). It means that a private constructor can be called from public constructors and even from static methods inside the same class.

1). Default Access Modifier

This modifier is declared by not mentioning any access modifier. The default access modifier thus means that the code which is inside the class itself, as well as the code inside classes in the same package as this class, can actually access the class, constructor, field or even the method which this modifier is assigned to. It is also thus known as the package access modifier. Various subclasses cannot actually access the methods and member variables (fields) in the superclass especially if these are methods and fields which are marked with a default access modifier unless the subclass is located in the same package as the superclass.


public class Clock {

long time =0;

}

public class ClockReader {

Clock clock = new Clock();

Public Long readClock {

return Clock.time;

}

}

The time field in the Clock class has no access modifier, which means it is implicitly assigned the default/package access modifier. Thus, the ClockReader class can read the time member variable of Clock object, provided that ClockReader and Clock are placed in the same Java package.

Read: Top 105 Angular Interview Questions and Answers In 2023

2). Protected Java Modifier

This modifier gives the same access like the default access modifier, with the addition that various subclasses can actually access the protected methods and other member variables of the superclass. This holds good even if the subclass is not located in the same package as the superclass.


public class Clock {

Protected long time =0;  //time in milliseconds

}

public class SmartClock () extends Clock {

Public long getTimeInSeconds() {

Return this.time / 1000;

}

}

The above figure shows that the SmartClock has a method called getTimeInSeconds() which can reach the time variable of the superclass Clock. This is possible even if Clock and SmartClock are not located in the same package, as the time field is highlighted with the protected Java access modifier.

3). Public Access Modifier

The Public Access Modifier stands for the fact that code can access the class, field, constructor and even the method, irrespective of the where the code was being located. Access to the code was in a different class and package.


Public Class Clock {

public long time = 0;

}

public class Clockreader {

Clock clock = new Clock();

public long readClock {

return clock.time;

}

}


The figure shows that the time field in the Clock class is marked with the public Java access modifier. Hence, the time field in the Clock can also be accessed by the ClockReader, irrespective of its package.

Class Access Modifiers

You should remember that the Java Access Modifier which is assigned to Java class has preference over any access modifiers which are assigned to fields, constructors and even the methods which belong to that class. If the class is marked with the default access modifier, then no other class outside the same Java package can have access to that class comprising its constructors, fields and even methods. There is no leverage gained when you declare these fields as public or even public static. The Private and Protected Java Access Modifiers cannot be assigned to any particular class. It is only to the constructors, methods, and fields which lie inside the class, can these be assigned. Classes can only have default package and public access modifier assigned to them.

Interface Access Modifiers

The interfaces in Java stand for the specification of fields and methods which are publicly available in classes which implement these interfaces. Hence the use of private and protected access modifiers in the interfaces is not possible. All the fields and methods in the interfaces are declared public if you let go an access modifier. Thus you cannot make use of the default access modifier either.

Read: A comprehensive guide for Java Developers Roles and Responsibilities | Updated!

Access Modifiers and Inheritance

When a subclass of some other class is created, then less accessible access modifiers cannot be assigned to the methods of the subclass. Thus, where it is not permitted to decrease the accessibility of the overridden method, expansion of accessibility of an overridden method is allowed. This is Java Inheritance in broad terms.

Non-Access Modifiers

Java has many non-access modifiers as well for achieving other functionality. These are:

  • Static: this modifier is used for the creation of class methods and variables.
  • Final: this modifier is used for finalization of implementation of classes, methods, and other variables.
  • Abstract: this modifier is used for the creation of abstract classes and methods.
  • Synchronized: this modifier is used for threads.

Conclusion

Thus, there are basically four types of access modifiers with their own functions and uses. Java access modifiers hence increase the class visibility. Also, if no keyword is mentioned, then it is a default access modifier. The four access modifiers of Java include public, private, protected, and even default.  Remember, private and protected keywords are not used for classes and interfaces.

Read: Serialization of Java Objects to XML Using XML Encoder/Decoder


fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

4 days 22 Nov 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

14 days 02 Dec 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

2 days 20 Nov 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

5 days 23 Nov 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

5 days 23 Nov 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

4 days 22 Nov 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

-0 day 18 Nov 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

4 days 22 Nov 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

12 days 30 Nov 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

5 days 23 Nov 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

39 days 27 Dec 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

4 days 22 Nov 2024

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews