SlideShare a Scribd company logo
JAVA
Topics for Today’s Session
Access Modifiers
Access Modifiers in Java
 In Java, access modifiers are used to set the accessibility
(visibility) of classes, interfaces, variables, methods,
constructors and data members.
 As the name suggests access modifiers in Java helps to
restrict the scope of a class, constructor , variable ,
method or data member.
 There are four types of access modifiers available in
java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
nChild class
inside
same package
Child class
inside
same
folder but
different
package
protected
private
public
default
Source Folder
Java package
public can be
accessed
anywhere
inheritsinherits
 If you do not specify any access level, it will be the
default.
 The data members, class or methods which are not
declared using any access modifiers i.e. having default
access modifier are accessible only within the same
package.
 The access level of a default modifier is only within the
package.
 It cannot be accessed from outside the package.
 Default access modifier means we do not explicitly
declare an access modifier for a class, field, method, etc.
//Java program to illustrate default modifier
package p1;
//Class Hello is having Default access modifier
class Hello {
void display() {
System.out.println("Hello World!");
} }
// program to illustrate error while using class from different package with
//default modifier
package p2;
import p1.*;
//This class is having default access modifier
class HelloNew {
public static void main(String args[]) {
//accessing class Hello from package p1
Hello obj = new Hello();
obj.display();
} }
Output:
Compile time error
 The private access modifier is specified using the
keyword private.
 The access level of a private modifier is only within the
class. It cannot be accessed from outside the class
 The methods or data members declared as private are
accessible only within the class in which they are
declared.
 Any other class of same package will not be able to
access these members.
 These cannot be inherited by subclasses and therefore
not accessible in subclasses.
 We can not override private members.
Example: private int x;
/*Pprogram to illustrate error while using class from different package
with private modifier */
package p1;
class A {
private void display() {
System.out.println("Hello Prathibha");
} }
class B {
public static void main(String args[]) {
A obj = new A();
//trying to access private method of another class
obj.display();
} }
Output:
error: display() has private access in A
obj.display();
//program accessing private members
class HelloData {
private String name; // private variable
}
class HlloMain {
public static void main(String[] main){
HelloData d = new HelloData(); // create an object of
HelloData
// access private variable and field from another class
d.name = "Prathibha Virtual Classes";
}
}
When we run the program, we will get the following error:
HelloMain.java:18: error: name has private access in HelloData
d.name = "Prathibha Virtual Classes”;
Protected Access Modifier
 A variable or method can be declared as protected using a
keyword ‘protected’.
 These can be accessed within the same package as well as
from subclasses.
 This is specially designed for supporting Inheritance.
 Protected access is used to access the variables or methods
visible everywhere in the same package in which it is
defined and also in the subclasses of other packages.
 Non subclasses of other packages cannot access protected
members.
Example: protected int x;
class Animal {
protected void display() { // protected method
System.out.println("I am an animal");
} }
class Dog extends Animal {
public static void main(String[] args) {
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
} }
Output:
I am an animal
//Program to illustrate protected modifier
package p1;
class A {
protected void display() {
System.out.println("Prathibha Virtual Classes");
} }
//Program to illustrate protected modifier
package p2;
import p1.*; //importing all classes in package p1
class B extends A { //Class B is subclass of A
public static void main(String args[]) {
B obj = new B();
obj.display();
} }
Output:
Prathibha Virtual Classes
 A variable or method can be declared as public using a
keyword ‘public’.
 The public access modifier has the widest scope among all
other access modifiers.
 Classes, methods or data members which are declared as
public are accessible from every where in the program. There
is no restriction on the scope of a public data members.
 The public methods or variables can be accessed within the
class and in other classes (outside) using objects and in all
packages.
Example: public int n;
public void sum ( ) {…}
//Java program to illustrate public modifier
package p1;
public class A {
public void display() {
System.out.println("Prathibha Virtual Classes");
}
}
package p2;
import p1.*;
class B {
public static void main(String args[]) {
A obj = new A;
obj.display();
}
}
Output:
Prathibha Virtual Classes
// Animal.java file public class
public class Animal {
public int legCount;
public void display() { // public method
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}}
// Main.java
public class Main {
public static void main( String[] args ) {
Animal ani = new Animal(); // accessing the public class
ani.legCount = 4; // accessing the public variable
ani.display(); // accessing the public method
} }
Output:
I am an animal.
I have 4 legs.
Private protected
 We may declare a member as “private protected”.
 This is used to access the member in all subclasses in all
packages.
 This is accessed in its own class and all the subclasses of
all the packages. But it is not accessed in other classes in
the same package and non sub classes in the other
packages.
Example private protected int x;
Access Modifier Visibility / Accessibility
public Visible everywhere in the program
friendly(default) Visible everywhere in the current package.
protected Visible everywhere in the current package and sub
classes in other packages
private Visible only in the class in which it is defined
private protected Visible in its own class and all the sub class of all the
packages
Accessibility of member using various
Access / Visibility modifiers:


Access modifiers in java
Ad

More Related Content

What's hot (20)

Java package
Java packageJava package
Java package
CS_GDRCST
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
Md.Al-imran Roton
 
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
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Static Members-Java.pptx
Static Members-Java.pptxStatic Members-Java.pptx
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Namespaces
NamespacesNamespaces
Namespaces
Sangeetha S
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Access specifier
Access specifierAccess specifier
Access specifier
zindadili
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
OOP Introduction with java programming language
OOP Introduction with java programming languageOOP Introduction with java programming language
OOP Introduction with java programming language
Md.Al-imran Roton
 
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
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
Spotle.ai
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
Michelle Anne Meralpis
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
Elizabeth Thomas
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
Muhammad Waqas
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Access specifier
Access specifierAccess specifier
Access specifier
zindadili
 

Similar to Access modifiers in java (20)

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
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Ashwin Thadani
 
Visibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptxVisibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptx
naazminshaikh1727
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
manish kumar
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPs
AdrizaBera
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
sushamaGavarskar1
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
MDRakibKhan3
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
Vinay Kumar
 
10 access control
10   access control10   access control
10 access control
dhrubo kayal
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
RatnaJava
 
Packages in java
Packages in javaPackages in java
Packages in java
Jerlin Sundari
 
PACKAGE.PPT12345678912345949745654646455
PACKAGE.PPT12345678912345949745654646455PACKAGE.PPT12345678912345949745654646455
PACKAGE.PPT12345678912345949745654646455
meetjaju38
 
Inheritance in c++theory
Inheritance in c++theoryInheritance in c++theory
Inheritance in c++theory
ProfSonaliGholveDoif
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
Hitesh-Java
 
Session 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access ModifiersSession 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access Modifiers
PawanMM
 
Packaes & interfaces
Packaes & interfacesPackaes & interfaces
Packaes & interfaces
yugandhar vadlamudi
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
LadallaRajKumar
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
Khaled Adnan
 
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
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Ashwin Thadani
 
Visibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptxVisibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptx
naazminshaikh1727
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
manish kumar
 
Power point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPsPower point presentation on access specifier in OOPs
Power point presentation on access specifier in OOPs
AdrizaBera
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
MDRakibKhan3
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
Vinay Kumar
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access ModifiersOOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
RatnaJava
 
PACKAGE.PPT12345678912345949745654646455
PACKAGE.PPT12345678912345949745654646455PACKAGE.PPT12345678912345949745654646455
PACKAGE.PPT12345678912345949745654646455
meetjaju38
 
OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers OOPs with Java - Packaging and Access Modifiers
OOPs with Java - Packaging and Access Modifiers
Hitesh-Java
 
Session 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access ModifiersSession 11 - OOP's with Java - Packaging and Access Modifiers
Session 11 - OOP's with Java - Packaging and Access Modifiers
PawanMM
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
Khaled Adnan
 
Ad

More from Madishetty Prathibha (14)

Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
Madishetty Prathibha
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
Madishetty Prathibha
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
Madishetty Prathibha
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
Madishetty Prathibha
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
Madishetty Prathibha
 
Operators in java
Operators in javaOperators in java
Operators in java
Madishetty Prathibha
 
Types of datastructures
Types of datastructuresTypes of datastructures
Types of datastructures
Madishetty Prathibha
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
Madishetty Prathibha
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
Madishetty Prathibha
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
Madishetty Prathibha
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
Madishetty Prathibha
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
Madishetty Prathibha
 
Java features
Java  features Java  features
Java features
Madishetty Prathibha
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
Madishetty Prathibha
 
Ad

Recently uploaded (20)

spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
Origin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theoriesOrigin of Brahmi script: A breaking down of various theories
Origin of Brahmi script: A breaking down of various theories
PrachiSontakke5
 
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFAMEDICAL BIOLOGY MCQS  BY. DR NASIR MUSTAFA
MEDICAL BIOLOGY MCQS BY. DR NASIR MUSTAFA
Dr. Nasir Mustafa
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)What is the Philosophy of Statistics? (and how I was drawn to it)
What is the Philosophy of Statistics? (and how I was drawn to it)
jemille6
 
How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18How to Configure Scheduled Actions in odoo 18
How to Configure Scheduled Actions in odoo 18
Celine George
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
UPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guideUPMVLE migration to ARAL. A step- by- step guide
UPMVLE migration to ARAL. A step- by- step guide
abmerca
 
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living WorkshopLDMMIA Reiki Yoga S5 Daily Living Workshop
LDMMIA Reiki Yoga S5 Daily Living Workshop
LDM Mia eStudios
 
Drugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdfDrugs in Anaesthesia and Intensive Care,.pdf
Drugs in Anaesthesia and Intensive Care,.pdf
crewot855
 
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
PHYSIOLOGY MCQS By DR. NASIR MUSTAFA (PHYSIOLOGY)
Dr. Nasir Mustafa
 
How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18How to Share Accounts Between Companies in Odoo 18
How to Share Accounts Between Companies in Odoo 18
Celine George
 
CNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscessCNS infections (encephalitis, meningitis & Brain abscess
CNS infections (encephalitis, meningitis & Brain abscess
Mohamed Rizk Khodair
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Cultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptxCultivation Practice of Turmeric in Nepal.pptx
Cultivation Practice of Turmeric in Nepal.pptx
UmeshTimilsina1
 
Botany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic ExcellenceBotany Assignment Help Guide - Academic Excellence
Botany Assignment Help Guide - Academic Excellence
online college homework help
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
BÀI TẬP BỔ TRỢ TIẾNG ANH 9 THEO ĐƠN VỊ BÀI HỌC - GLOBAL SUCCESS - CẢ NĂM (TỪ...
Nguyen Thanh Tu Collection
 

Access modifiers in java

  • 2. Topics for Today’s Session Access Modifiers
  • 3. Access Modifiers in Java  In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces, variables, methods, constructors and data members.  As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor , variable , method or data member.  There are four types of access modifiers available in java: 1. Default – No keyword required 2. Private 3. Protected 4. Public
  • 4. nChild class inside same package Child class inside same folder but different package protected private public default Source Folder Java package public can be accessed anywhere inheritsinherits
  • 5.  If you do not specify any access level, it will be the default.  The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package.  The access level of a default modifier is only within the package.  It cannot be accessed from outside the package.  Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
  • 6. //Java program to illustrate default modifier package p1; //Class Hello is having Default access modifier class Hello { void display() { System.out.println("Hello World!"); } } // program to illustrate error while using class from different package with //default modifier package p2; import p1.*; //This class is having default access modifier class HelloNew { public static void main(String args[]) { //accessing class Hello from package p1 Hello obj = new Hello(); obj.display(); } } Output: Compile time error
  • 7.  The private access modifier is specified using the keyword private.  The access level of a private modifier is only within the class. It cannot be accessed from outside the class  The methods or data members declared as private are accessible only within the class in which they are declared.  Any other class of same package will not be able to access these members.  These cannot be inherited by subclasses and therefore not accessible in subclasses.  We can not override private members. Example: private int x;
  • 8. /*Pprogram to illustrate error while using class from different package with private modifier */ package p1; class A { private void display() { System.out.println("Hello Prathibha"); } } class B { public static void main(String args[]) { A obj = new A(); //trying to access private method of another class obj.display(); } } Output: error: display() has private access in A obj.display();
  • 9. //program accessing private members class HelloData { private String name; // private variable } class HlloMain { public static void main(String[] main){ HelloData d = new HelloData(); // create an object of HelloData // access private variable and field from another class d.name = "Prathibha Virtual Classes"; } } When we run the program, we will get the following error: HelloMain.java:18: error: name has private access in HelloData d.name = "Prathibha Virtual Classes”;
  • 10. Protected Access Modifier  A variable or method can be declared as protected using a keyword ‘protected’.  These can be accessed within the same package as well as from subclasses.  This is specially designed for supporting Inheritance.  Protected access is used to access the variables or methods visible everywhere in the same package in which it is defined and also in the subclasses of other packages.  Non subclasses of other packages cannot access protected members. Example: protected int x;
  • 11. class Animal { protected void display() { // protected method System.out.println("I am an animal"); } } class Dog extends Animal { public static void main(String[] args) { // create an object of Dog class Dog dog = new Dog(); // access protected method dog.display(); } } Output: I am an animal
  • 12. //Program to illustrate protected modifier package p1; class A { protected void display() { System.out.println("Prathibha Virtual Classes"); } } //Program to illustrate protected modifier package p2; import p1.*; //importing all classes in package p1 class B extends A { //Class B is subclass of A public static void main(String args[]) { B obj = new B(); obj.display(); } } Output: Prathibha Virtual Classes
  • 13.  A variable or method can be declared as public using a keyword ‘public’.  The public access modifier has the widest scope among all other access modifiers.  Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members.  The public methods or variables can be accessed within the class and in other classes (outside) using objects and in all packages. Example: public int n; public void sum ( ) {…}
  • 14. //Java program to illustrate public modifier package p1; public class A { public void display() { System.out.println("Prathibha Virtual Classes"); } } package p2; import p1.*; class B { public static void main(String args[]) { A obj = new A; obj.display(); } } Output: Prathibha Virtual Classes
  • 15. // Animal.java file public class public class Animal { public int legCount; public void display() { // public method System.out.println("I am an animal."); System.out.println("I have " + legCount + " legs."); }} // Main.java public class Main { public static void main( String[] args ) { Animal ani = new Animal(); // accessing the public class ani.legCount = 4; // accessing the public variable ani.display(); // accessing the public method } } Output: I am an animal. I have 4 legs.
  • 16. Private protected  We may declare a member as “private protected”.  This is used to access the member in all subclasses in all packages.  This is accessed in its own class and all the subclasses of all the packages. But it is not accessed in other classes in the same package and non sub classes in the other packages. Example private protected int x;
  • 17. Access Modifier Visibility / Accessibility public Visible everywhere in the program friendly(default) Visible everywhere in the current package. protected Visible everywhere in the current package and sub classes in other packages private Visible only in the class in which it is defined private protected Visible in its own class and all the sub class of all the packages Accessibility of member using various Access / Visibility modifiers:
  翻译: