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

java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
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 JavaMOHIT AGARWAL
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword pptVinod Kumar
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Paumil Patel
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statementsKuppusamy P
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In JavaManish Sahu
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in javasawarkar17
 

What's hot (20)

java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
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
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Java conditional statements
Java conditional statementsJava conditional statements
Java conditional statements
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Abstraction in java
Abstraction in javaAbstraction in java
Abstraction in java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance 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
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiersKhaled Adnan
 

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
 
Java access modifiers
Java access modifiersJava access modifiers
Java access modifiers
 
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
 

More from Madishetty Prathibha

More from Madishetty Prathibha (13)

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
 
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

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
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
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
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
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
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
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

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: