SlideShare a Scribd company logo
Access Modifiers in Java
Sourabrata Mukherjee
Topics:
● Why Access Modifiers?
● Private
● Default (package)
● Protected
● Public
● Access Modifiers and Inheritance
● Access Modifiers on Local Variables
Why Access Modifiers?
The use of modifiers goes to the core concepts of encapsulation, aka 'data hiding'
in object-oriented development. Variables should never be public. That is the
whole point of private/protected modifiers on them: to prevent direct access to
the variables themselves. You provide methods to manipulate variables. A method
has to be public in order to allow other programmers (or classes) access to that
data. But by using methods, you can control how a variable is manipulated. Which
is the entire point because you've hidden the details of the variable behind the
method.
Continue..
Let Suppose you have class which contains two variable age and name. Now you
have created getter setter for these variable. It is obvious that variable which we
declared we will mark it as private, Why because i don't want to give the
accessibility of that variable to other class directly. Now The question is why i
don't want to give accessibility directly to other class?. The Answer is because i
want to control my variable. If i will give direct accessibility to other class, Other
class can assign age as negative which is not good, age cannot be a negative
value. Hence to control this thing i am exposing getter and setter method.
Continue..
Other class object will call my setter method and supply value. Inside method i can
control the value like if age is negative simply assign 0 or if age is more than 200
throw exception saying age cannot be 200. Now what is another class object want
to read data from variable. For that i have given one getter method which would be
public in nature. Since my variable is private hence other class object cannot
directly access my variable hence this getter method is required which will simply
return the variable. Access modifier are used to control the visibility of any
variable or method and this is necessary .
Private
The private access modifier is accessible only within class.
A class cannot be private or protected except nested class.
If you make any class constructor private, you cannot create the instance of that
class from outside the class.
Continue..
private Constructors:
If a constructor in a class is assigned the private Java access modifier, that
means that the constructor cannot be called from anywhere outside the class. A
private constructor can still get called from other constructors, or from static
methods in the same class. Here is an example,
Continue..
public class Clock {
private long time = 0;
private Clock(long time) {
this.time = time;
}
public Clock(long time, long timeOffset) {
this(time);
this.time += timeOffset;
}
public static Clock newClock() {
return new Clock(System.currentTimeMillis());
}
Continue..
This version of the Clock class contains a private constructor and a public
constructor. The private constructor is called from the public constructor (the
statement this();). The private constructor is also called from the static method
newClock(). The above example only serves to show you that a private constructor
can be called from public constructors and from static methods inside the same
class. Do not perceive the above example as an example of clever design in any
way.
Default
If you don't use any modifier, it is treated as default by default. The default
modifier is accessible only within package.
The default Java access modifier is declared by not writing any access modifier at
all. The default access modifier means that code inside the class itself as well as
code inside classes in the same package as this class, can access the class, field,
constructor or method which the default access modifier is assigned to.
Therefore, the default access modifier is also sometimes referred to as the
package access modifier.
Protected
The protected access modifier is accessible within package and outside the
package but through inheritance only. The protected access modifier can be
applied on the data member, method and constructor. It can't be applied on the
class.
The protected access modifier provides the same access as the default access
modifier, with the addition that subclasses can access protected methods and
member variables (fields) of the superclass. This is true even if the subclass is not
located in the same package as the superclass.
Public
The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
The accessing code can be in a different class and different package.
Access Modifiers and Inheritance
When you create a subclass of some class, the methods in the subclass cannot
have less accessible access modifiers assigned to them than they had in the
superclass. For instance, if a method in the superclass is public then it must be
public in the subclass too, in case the subclass overrides the method. If a method
in the superclass is protected then it must be either protected or public in the
subclass. While it is not allowed to decrease accessibility of an overridden
method, it is allowed to expand accessibility of an overridden method. For
instance, if a method is assigned the default access modifier in the superclass,
then it is allowed to assign the overridden method in the subclass the public
access modifier.
Access Modifiers on Local Variables
No Access Modifiers can be applied to local variables. Only final can be applied to
a local variable which is a Non Access Modifier .
Conclusion
Thank You
Ad

More Related Content

What's hot (20)

OOP java
OOP javaOOP java
OOP java
xball977
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Madishetty Prathibha
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
C# Types of classes
C# Types of classesC# Types of classes
C# Types of classes
Prem Kumar Badri
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
File handling
File handlingFile handling
File handling
priya_trehan
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
AsifMulani17
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
Elizabeth alexander
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Abishek Purushothaman
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
anshu_atri
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
INHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptxINHERITANCE IN JAVA.pptx
INHERITANCE IN JAVA.pptx
NITHISG1
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
AsifMulani17
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 
Super and final in java
Super and final in javaSuper and final in java
Super and final in java
anshu_atri
 

Similar to Access modifiers in java (20)

Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
MDRakibKhan3
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
Margaret Mary
 
Imp Key.pptx very easy to learn go for it
Imp Key.pptx very easy to learn go for itImp Key.pptx very easy to learn go for it
Imp Key.pptx very easy to learn go for it
dwivedyp
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
Thakur Amit Tomer
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Gaurav Mehta
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 
OOP presentation.pptx
OOP presentation.pptxOOP presentation.pptx
OOP presentation.pptx
AbulHasnatHridoy2211
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
homeworkping9
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdf
sanjeevtandonsre
 
3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx
carold12
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
MD SALEEM QAISAR
 
Chapter 8 java
Chapter 8 javaChapter 8 java
Chapter 8 java
Ahmad sohail Kakar
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
DevLabs Alliance
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
devlabsalliance
 
Learning PHP Basics Part 2
Learning PHP Basics Part 2Learning PHP Basics Part 2
Learning PHP Basics Part 2
ProdigyView
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
COMSATS Institute of Information Technology
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
Aravind NC
 
Chapter 9 java
Chapter 9 javaChapter 9 java
Chapter 9 java
Ahmad sohail Kakar
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
MDRakibKhan3
 
Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
Margaret Mary
 
Imp Key.pptx very easy to learn go for it
Imp Key.pptx very easy to learn go for itImp Key.pptx very easy to learn go for it
Imp Key.pptx very easy to learn go for it
dwivedyp
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
Gaurav Mehta
 
Chapter 05 polymorphism extra
Chapter 05 polymorphism extraChapter 05 polymorphism extra
Chapter 05 polymorphism extra
Nurhanna Aziz
 
116824015 java-j2 ee
116824015 java-j2 ee116824015 java-j2 ee
116824015 java-j2 ee
homeworkping9
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
Terry Yoast
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
Arun Vasanth
 
Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdf
sanjeevtandonsre
 
3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx3) Distinguish among various methods to implement access controlsSolut.docx
3) Distinguish among various methods to implement access controlsSolut.docx
carold12
 
Inheritance and its types In Java
Inheritance and its types In JavaInheritance and its types In Java
Inheritance and its types In Java
MD SALEEM QAISAR
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
DevLabs Alliance
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
devlabsalliance
 
Learning PHP Basics Part 2
Learning PHP Basics Part 2Learning PHP Basics Part 2
Learning PHP Basics Part 2
ProdigyView
 
Master of Computer Application (MCA) – Semester 4 MC0078
Master of Computer Application (MCA) – Semester 4  MC0078Master of Computer Application (MCA) – Semester 4  MC0078
Master of Computer Application (MCA) – Semester 4 MC0078
Aravind NC
 
Ad

Recently uploaded (20)

Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Lumion Pro Crack + 2025 Activation Key Free Code
Lumion Pro Crack + 2025 Activation Key Free CodeLumion Pro Crack + 2025 Activation Key Free Code
Lumion Pro Crack + 2025 Activation Key Free Code
raheemk1122g
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo
 
iTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation KeyiTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation Key
raheemk1122g
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Applying AI in Marketo: Practical Strategies and Implementation
Applying AI in Marketo: Practical Strategies and ImplementationApplying AI in Marketo: Practical Strategies and Implementation
Applying AI in Marketo: Practical Strategies and Implementation
BradBedford3
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Why CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Why CoTester Is the AI Testing Tool QA Teams Can’t IgnoreWhy CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Why CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Shubham Joshi
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
Bridging Sales & Marketing Gaps with IInfotanks’ Salesforce Account Engagemen...
jamesmartin143256
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
Time Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project TechniquesTime Estimation: Expert Tips & Proven Project Techniques
Time Estimation: Expert Tips & Proven Project Techniques
Livetecs LLC
 
GC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance EngineeringGC Tuning: A Masterpiece in Performance Engineering
GC Tuning: A Masterpiece in Performance Engineering
Tier1 app
 
Lumion Pro Crack + 2025 Activation Key Free Code
Lumion Pro Crack + 2025 Activation Key Free CodeLumion Pro Crack + 2025 Activation Key Free Code
Lumion Pro Crack + 2025 Activation Key Free Code
raheemk1122g
 
Welcome to QA Summit 2025.
Welcome to QA Summit 2025.Welcome to QA Summit 2025.
Welcome to QA Summit 2025.
QA Summit
 
Download 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-ActivatedDownload 4k Video Downloader Crack Pre-Activated
Download 4k Video Downloader Crack Pre-Activated
Web Designer
 
Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509Orion Context Broker introduction 20250509
Orion Context Broker introduction 20250509
Fermin Galan
 
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo Ltd. - Introduction - Mobile application, web, custom software develo...
Codingo
 
iTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation KeyiTop VPN With Crack Lifetime Activation Key
iTop VPN With Crack Lifetime Activation Key
raheemk1122g
 
wAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptxwAIred_LearnWithOutAI_JCON_14052025.pptx
wAIred_LearnWithOutAI_JCON_14052025.pptx
SimonedeGijt
 
Solar-wind hybrid engery a system sustainable power
Solar-wind  hybrid engery a system sustainable powerSolar-wind  hybrid engery a system sustainable power
Solar-wind hybrid engery a system sustainable power
bhoomigowda12345
 
Applying AI in Marketo: Practical Strategies and Implementation
Applying AI in Marketo: Practical Strategies and ImplementationApplying AI in Marketo: Practical Strategies and Implementation
Applying AI in Marketo: Practical Strategies and Implementation
BradBedford3
 
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb ClarkDeploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Deploying & Testing Agentforce - End-to-end with Copado - Ewenb Clark
Peter Caitens
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Why CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Why CoTester Is the AI Testing Tool QA Teams Can’t IgnoreWhy CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Why CoTester Is the AI Testing Tool QA Teams Can’t Ignore
Shubham Joshi
 
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-RuntimeReinventing Microservices Efficiency and Innovation with Single-Runtime
Reinventing Microservices Efficiency and Innovation with Single-Runtime
Natan Silnitsky
 
Let's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured ContainersLet's Do Bad Things to Unsecured Containers
Let's Do Bad Things to Unsecured Containers
Gene Gotimer
 
Ad

Access modifiers in java

  • 1. Access Modifiers in Java Sourabrata Mukherjee
  • 2. Topics: ● Why Access Modifiers? ● Private ● Default (package) ● Protected ● Public ● Access Modifiers and Inheritance ● Access Modifiers on Local Variables
  • 3. Why Access Modifiers? The use of modifiers goes to the core concepts of encapsulation, aka 'data hiding' in object-oriented development. Variables should never be public. That is the whole point of private/protected modifiers on them: to prevent direct access to the variables themselves. You provide methods to manipulate variables. A method has to be public in order to allow other programmers (or classes) access to that data. But by using methods, you can control how a variable is manipulated. Which is the entire point because you've hidden the details of the variable behind the method.
  • 4. Continue.. Let Suppose you have class which contains two variable age and name. Now you have created getter setter for these variable. It is obvious that variable which we declared we will mark it as private, Why because i don't want to give the accessibility of that variable to other class directly. Now The question is why i don't want to give accessibility directly to other class?. The Answer is because i want to control my variable. If i will give direct accessibility to other class, Other class can assign age as negative which is not good, age cannot be a negative value. Hence to control this thing i am exposing getter and setter method.
  • 5. Continue.. Other class object will call my setter method and supply value. Inside method i can control the value like if age is negative simply assign 0 or if age is more than 200 throw exception saying age cannot be 200. Now what is another class object want to read data from variable. For that i have given one getter method which would be public in nature. Since my variable is private hence other class object cannot directly access my variable hence this getter method is required which will simply return the variable. Access modifier are used to control the visibility of any variable or method and this is necessary .
  • 6. Private The private access modifier is accessible only within class. A class cannot be private or protected except nested class. If you make any class constructor private, you cannot create the instance of that class from outside the class.
  • 7. Continue.. private Constructors: If a constructor in a class is assigned the private Java access modifier, that means that the constructor cannot be called from anywhere outside the class. A private constructor can still get called from other constructors, or from static methods in the same class. Here is an example,
  • 8. Continue.. public class Clock { private long time = 0; private Clock(long time) { this.time = time; } public Clock(long time, long timeOffset) { this(time); this.time += timeOffset; } public static Clock newClock() { return new Clock(System.currentTimeMillis()); }
  • 9. Continue.. This version of the Clock class contains a private constructor and a public constructor. The private constructor is called from the public constructor (the statement this();). The private constructor is also called from the static method newClock(). The above example only serves to show you that a private constructor can be called from public constructors and from static methods inside the same class. Do not perceive the above example as an example of clever design in any way.
  • 10. Default If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. The default Java access modifier is declared by not writing any access modifier at all. The default access modifier means that code inside the class itself as well as code inside classes in the same package as this class, can access the class, field, constructor or method which the default access modifier is assigned to. Therefore, the default access modifier is also sometimes referred to as the package access modifier.
  • 11. Protected The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. The protected access modifier provides the same access as the default access modifier, with the addition that subclasses can access protected methods and member variables (fields) of the superclass. This is true even if the subclass is not located in the same package as the superclass.
  • 12. Public The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. The accessing code can be in a different class and different package.
  • 13. Access Modifiers and Inheritance When you create a subclass of some class, the methods in the subclass cannot have less accessible access modifiers assigned to them than they had in the superclass. For instance, if a method in the superclass is public then it must be public in the subclass too, in case the subclass overrides the method. If a method in the superclass is protected then it must be either protected or public in the subclass. While it is not allowed to decrease accessibility of an overridden method, it is allowed to expand accessibility of an overridden method. For instance, if a method is assigned the default access modifier in the superclass, then it is allowed to assign the overridden method in the subclass the public access modifier.
  • 14. Access Modifiers on Local Variables No Access Modifiers can be applied to local variables. Only final can be applied to a local variable which is a Non Access Modifier .
  翻译: