SlideShare a Scribd company logo
1 of 19
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

More Related Content

What's hot

Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling pptJavabynataraJ
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaRahulAnanda1
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiersKhaled Adnan
 
Access modifiers
Access modifiersAccess modifiers
Access modifiersJadavsejal
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
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
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAMehak Tawakley
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaArafat Hossan
 

What's hot (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
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)
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 

Similar to Access modifiers in java

Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptxMargaret Mary
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in javaAshwin Thadani
 
Visibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptxVisibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptxnaazminshaikh1727
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packagesmanish 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 OOPsAdrizaBera
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptxMDRakibKhan3
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesVinay 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 ModifiersRatnaJava
 
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 ModifiersPawanMM
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++RAJ KUMAR
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxRudranilDas11
 

Similar to Access modifiers in java (20)

Access Modifier.pptx
Access Modifier.pptxAccess Modifier.pptx
Access Modifier.pptx
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Visibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptxVisibility Modifiers for Access Control.pptx
Visibility Modifiers for Access Control.pptx
 
Lecture 9 access modifiers and packages
Lecture   9 access modifiers and packagesLecture   9 access modifiers and packages
Lecture 9 access modifiers and packages
 
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
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
 
10 access control
10   access control10   access control
10 access control
 
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
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Inheritance in c++theory
Inheritance in c++theoryInheritance in c++theory
Inheritance in c++theory
 
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
 
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
 
Packaes & interfaces
Packaes & interfacesPackaes & interfaces
Packaes & interfaces
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 

More from Madishetty Prathibha

More from Madishetty Prathibha (14)

Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Classes objects in java
Classes objects in javaClasses objects in java
Classes objects in java
 
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
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Types of datastructures
Types of datastructuresTypes of datastructures
Types of datastructures
 
Introduction to algorithms
Introduction to algorithmsIntroduction to algorithms
Introduction to algorithms
 
Java data types, variables and jvm
Java data types, variables and jvm Java data types, variables and jvm
Java data types, variables and jvm
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
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
 
Java features
Java  features Java  features
Java features
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxLigayaBacuel1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Planning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptxPlanning a health career 4th Quarter.pptx
Planning a health career 4th Quarter.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 

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: