Today's Offer - Java Certification Training - Enroll at Flat 10% Off.

- 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: How to Start a Career as a Java Developer or Programmer

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: Node.JS Interview Questions and Answers for Fresher, Experienced

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: What is Java Exponent? How to Do Exponents in Java?

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.


    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

4 days 24 Nov 2019

DevOps

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

Upcoming Class

5 days 25 Nov 2019

Data Science

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

Upcoming Class

5 days 25 Nov 2019

Hadoop

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

Upcoming Class

6 days 26 Nov 2019

Salesforce

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

Upcoming Class

-1 day 19 Nov 2019

Course for testing

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

Upcoming Class

34 days 24 Dec 2019

QA

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

Upcoming Class

13 days 03 Dec 2019

Business Analyst

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

Upcoming Class

5 days 25 Nov 2019

SQL Server

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

Upcoming Class

-1 day 19 Nov 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews