SlideShare a Scribd company logo
Java Access Modifiers
            SCJP/OCJP exam objectives – 1.1,1.3,1.4




                                              By,
                                       Srinivas Reddy.S
www.JAVA9S.com
Access Modifiers - Importance


         GoogleSearch
             int pageRank;
               int index;
    getSearchResults(String query){}
   calculatePageRankAndIndexPages
                   (){}
Access Modifiers
•   public
•   protected
•   default
•   private
Access Modifiers - Importance
• Access modifiers helps to implement the
  concept of encapsulation in OOPs.
• Encapsulation helps to hide the data and
  behavior.
• Access Modifiers affect the accessibility at
  two levels :
  • Class
  • Members(methods and instance variables)
Access Modifiers – at class level
public
• When a class is marked as public, it is visible to all
  other classes which are inside and outside the
  package. – Visible to everyone..

 package com.java9s.Engines;           package com.java9s.cars;
                                       import com.java9s.Engines.Engine;
 public class Engine{
          public int engine1000cc(){   public class Ford{
                   int rpmCount=…..;            void moveFast(){
                   return rpmCount;               Engine e = new Engine();
          }                                     int rpm = e.engine3000cc()
          public int engine3000cc(){            //move with speed related to
                   int rpmCount=…..;            //rpm
                   return rpmCount;             }
          }                            }
 }
public - class level
• A class marked as public is be accessible to all
  classes in other packages, but should
  mention the import statement.
• There is no need for an import statement
  when a class inside the same package uses
  the class marked as public
default – class level
• Default access has no key word.
• When there is no access modifier declared,
  the access is default level access.
• The classes marked with default access are
  visible only to the classes inside the same
  package.
default – class level
package com.java9s.bank;
class InterestRates{                                When there is no
      double creditCardInterest(){                  access modifier specified
      …….;                                          - The access is default level
      }

      double homeLoanInterest(){
      ……;
      }                  package com.java9s.bank;
}                        public class customerBanking{
                             double calculateHomeLoan(){
                             InterestRates i = new InterestRates();
                             double interest = i.creditCardInterest();
                             //calculate the home loan of customer
                             return x;
                              }
                         }
default – class level
package com.java9s.bank;
class InterestRates{
        double creditCardInterest(){
        …….;
        }

          double homeLoadInterest(){
          ……;
          }                       package com.java9s.Customerbank;
}                                 public class customerBanking{
                                      double calculateHomeLoan(){
                                      InterestRates i = new InterestRates();
 The accessing class is not           double interest = i.creditCardInterest();
 in the same package. So, the class
                                      //calculate the home loan of customer
 With default will not be visible
                                      return x;
                                       }
                                  }
protected and private – class level
***protected and private access modifiers are
  not applicable to the class level
  declaration***
Access modifiers – member level
(methods and instance variables)
public – member level
• A member with public access is visible to all
  the classes inside and outside package.
• The class in which the member exists should
  be is visible to the accessing class.
public – member level
package com.java9s.Engines;           package com.java9s.cars;
                                      import com.java9s.Engines.Engine;
public class Engine{
         public int engine1000cc(){   public class Ford{
                  int rpmCount=…..;            void moveFast(){
                  return rpmCount;               Engine e = new Engine();
         }                                     int rpm = e.engine3000cc()
         public int engine3000cc(){            //move with speed related to
                  int rpmCount=…..;            //rpm
                  return rpmCount;             }
         }                            }
}

         •Check if the class itself is accessible
         •Check if the import statement is used to import the class(if
                   accessed from other package)
         •Finally- check if the member is accessible
public – member level
package com.java9s.Engines;           package com.java9s.cars;
                                      import com.java9s.Engines.Engine;
class Engine{
         public int engine1000cc(){   public class Ford{
                  int rpmCount=…..;            void moveFast(){
                  return rpmCount;               Engine e = new Engine();
         }                                     int rpm = e.engine3000cc()
         public int engine3000cc(){            //move with speed related to
                  int rpmCount=…..;            //rpm
                  return rpmCount;             }
         }                            }
}


     The class engine is having default access and will not be visible to Ford
default – member level
• A member marked with default access will be
  visible to the classes that are in the same
  package.
default – member level
package com.java9s.bank;
class InterestRates{
      double creditCardInterest(){
      …….;
      }

      double homeLoadInterest(){
      ……;
      }                  package com.java9s.bank;
}                        public class customerBanking{
                             double calculateHomeLoan(){
                             InterestRates i = new InterestRates();
                             double interest = i.creditCardInterest();
                             //calculate the home loan of customer
                             return x;
                              }
                         }
protected – member level
• A member marked as protected is visible to
  all classes in the same package(Just like
  default).
• protected members are also accessible to
  classes outside the package, but the
  accessing class should be a subclass of the
  member class.
protected- member level
                                      package com.java9s.cars;
 package com.java9s.cars;
 public class Car{                    public class Benz{
   protected int speed;                 int move(){
 }                                          Car c = new Car();
package com.java9s.fastCars;                return c.speed;
public class Ferrari extends Car{           }
         int moveFast(){
         return super.speed;          }
         }
   int move(){                      Note: The protected members can be
         Car c= new Car();          accessed only by the subclasses in other
         c.speed;                   packages and can invoke the members
                                    only through inheritance mode.
         }
                                    Not by creating an instance.
}
private – member level
• When a member is marked as private, it is
  only visible to other members inside the
  same class.
• Other classes inside and outside the package
  will not be able to access the private
  members of a class.
private – member level

 public class Car{
   private String keyCode;
 }


public class Theif{          keyCode variable is not
      void steal(){          visible outside the class Car

      Car c = new Car();
      c.keyCode;
      }
}
protected and private – class level
***protected and private access modifiers are
  not applicable to the class level
  declaration***


                 ???
Access Modifiers - summary
Visibility                      public   protected     default   private
From the same class             Yes      Yes           Yes       Yes

From a class in same package    Yes      Yes           Yes       No



From a class from outside the   Yes      No            No        No
package



From a subclass outside the     Yes      Yes(Only      No        No
package                                  through
                                         inheritance
                                         mode)
From a subclass in the same     Yes      Yes           Yes       No
package
Access Modifiers – Local Variables
public class Calculator{
   public int addition(int a, int b){
  int c = a+b;
  return c;
                      C is a local variable and only lives till the method
  }                   Executes.

}

No access modifiers should be applied for Local variables
Thank you
   Follow me on to get more updates on latest video posts
   Subscribe on

   http://www.youtube.com/user/java9s
   Twitter :   @java9s

   facebook: www.facebook.com/java9s




www.JAVA9S.com

More Related Content

What's hot (20)

PPTX
Method overloading
Lovely Professional University
 
PPTX
Interface in java
PhD Research Scholar
 
PPT
Inheritance in java
Lovely Professional University
 
PPT
Abstract class in java
Lovely Professional University
 
PPTX
This keyword in java
Hitesh Kumar
 
PPS
Java Exception handling
kamal kotecha
 
PPTX
File handling
priya_trehan
 
PPT
Final keyword in java
Lovely Professional University
 
PPT
Object and class
mohit tripathi
 
PPT
Exception Handling in JAVA
SURIT DATTA
 
PPTX
Java constructors
QUONTRASOLUTIONS
 
PPTX
Constructor in java
Pavith Gunasekara
 
PDF
Basic Java Programming
Math-Circle
 
PPTX
Classes objects in java
Madishetty Prathibha
 
PDF
Methods in Java
Jussi Pohjolainen
 
PPTX
Inheritance in java
RahulAnanda1
 
PPT
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
PPTX
Inheritance in JAVA PPT
Pooja Jaiswal
 
PPTX
Constructor ppt
Vinod Kumar
 
PPTX
Inheritance in c++
Vineeta Garg
 
Method overloading
Lovely Professional University
 
Interface in java
PhD Research Scholar
 
Inheritance in java
Lovely Professional University
 
Abstract class in java
Lovely Professional University
 
This keyword in java
Hitesh Kumar
 
Java Exception handling
kamal kotecha
 
File handling
priya_trehan
 
Final keyword in java
Lovely Professional University
 
Object and class
mohit tripathi
 
Exception Handling in JAVA
SURIT DATTA
 
Java constructors
QUONTRASOLUTIONS
 
Constructor in java
Pavith Gunasekara
 
Basic Java Programming
Math-Circle
 
Classes objects in java
Madishetty Prathibha
 
Methods in Java
Jussi Pohjolainen
 
Inheritance in java
RahulAnanda1
 
PHP - Introduction to Object Oriented Programming with PHP
Vibrant Technologies & Computers
 
Inheritance in JAVA PPT
Pooja Jaiswal
 
Constructor ppt
Vinod Kumar
 
Inheritance in c++
Vineeta Garg
 

Viewers also liked (19)

PPTX
Access modifiers in java
Sourabrata Mukherjee
 
PDF
12 java modifiers
Federico Russo
 
PDF
Learn Java Part 10
Gurpreet singh
 
PPT
Access specifier in java
Kaml Sah
 
PPTX
software project management Waterfall model
REHMAT ULLAH
 
PPTX
Bluetooth technology
Rohit Roy
 
PPTX
Event Handling in java
Google
 
PPT
Bluetooth
Sumeet Rayat
 
PPT
Classical problem of synchronization
Shakshi Ranawat
 
PPTX
Visibility control in java
Tech_MX
 
PPTX
Bluetooth - Overview
Shobana Pattabiraman
 
PDF
Access modifiers in java
Muthukumaran Subramanian
 
DOCX
Bluetooth wi fi wi max 2, 3
jandrewsxu
 
PPTX
Awt
Rakesh Patil
 
PPT
Wi-Fi vs Bluetooth
Arun ACE
 
PPT
Waterfall Model
university of education,Lahore
 
PPTX
Waterfall model ppt final
shiva krishna
 
PPTX
Waterfall model
BHARGAV VISANI
 
PPTX
Wi-Fi Technology
Naveen Kumar
 
Access modifiers in java
Sourabrata Mukherjee
 
12 java modifiers
Federico Russo
 
Learn Java Part 10
Gurpreet singh
 
Access specifier in java
Kaml Sah
 
software project management Waterfall model
REHMAT ULLAH
 
Bluetooth technology
Rohit Roy
 
Event Handling in java
Google
 
Bluetooth
Sumeet Rayat
 
Classical problem of synchronization
Shakshi Ranawat
 
Visibility control in java
Tech_MX
 
Bluetooth - Overview
Shobana Pattabiraman
 
Access modifiers in java
Muthukumaran Subramanian
 
Bluetooth wi fi wi max 2, 3
jandrewsxu
 
Wi-Fi vs Bluetooth
Arun ACE
 
Waterfall model ppt final
shiva krishna
 
Waterfall model
BHARGAV VISANI
 
Wi-Fi Technology
Naveen Kumar
 
Ad

Similar to Java access modifiers (20)

PPTX
Lecture 9 access modifiers and packages
manish kumar
 
PPT
Inheritance and Polymorphism
BG Java EE Course
 
PPTX
Inheritance
Tech_MX
 
PDF
Chapter 03 enscapsulation
Nurhanna Aziz
 
PDF
CHAPTER 3 part1.pdf
FacultyAnupamaAlagan
 
PPTX
Imp Key.pptx very easy to learn go for it
dwivedyp
 
PPTX
Module1 elementary concepts of objects and classes
MersonSir
 
PPT
Javapackages 4th semester
Varendra University Rajshahi-bangladesh
 
PDF
First fare 2011 frc-java-introduction
Oregon FIRST Robotics
 
PDF
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
PPT
Java Classes methods and inheritance
Srinivas Reddy
 
PDF
Classes and Object Concept Object Oriented Programming in Java
gedeios
 
PPT
Java: Class Design Examples
Tareq Hasan
 
PPTX
Pj01 x-classes and objects
SasidharaRaoMarrapu
 
PPTX
OOP in Java Presentation.pptx
mrxyz19
 
PPT
Inheritance
ankush_kumar
 
PPTX
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
PPTX
Power point presentation on access specifier in OOPs
AdrizaBera
 
PPTX
2- Introduction to java II
Ghadeer AlHasan
 
PPT
encapsulation and abstraction
ALIZAPARVIN
 
Lecture 9 access modifiers and packages
manish kumar
 
Inheritance and Polymorphism
BG Java EE Course
 
Inheritance
Tech_MX
 
Chapter 03 enscapsulation
Nurhanna Aziz
 
CHAPTER 3 part1.pdf
FacultyAnupamaAlagan
 
Imp Key.pptx very easy to learn go for it
dwivedyp
 
Module1 elementary concepts of objects and classes
MersonSir
 
Javapackages 4th semester
Varendra University Rajshahi-bangladesh
 
First fare 2011 frc-java-introduction
Oregon FIRST Robotics
 
Java Programming - 05 access control in java
Danairat Thanabodithammachari
 
Java Classes methods and inheritance
Srinivas Reddy
 
Classes and Object Concept Object Oriented Programming in Java
gedeios
 
Java: Class Design Examples
Tareq Hasan
 
Pj01 x-classes and objects
SasidharaRaoMarrapu
 
OOP in Java Presentation.pptx
mrxyz19
 
Inheritance
ankush_kumar
 
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
Power point presentation on access specifier in OOPs
AdrizaBera
 
2- Introduction to java II
Ghadeer AlHasan
 
encapsulation and abstraction
ALIZAPARVIN
 
Ad

Recently uploaded (20)

PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 

Java access modifiers

  • 1. Java Access Modifiers SCJP/OCJP exam objectives – 1.1,1.3,1.4 By, Srinivas Reddy.S www.JAVA9S.com
  • 2. Access Modifiers - Importance GoogleSearch int pageRank; int index; getSearchResults(String query){} calculatePageRankAndIndexPages (){}
  • 3. Access Modifiers • public • protected • default • private
  • 4. Access Modifiers - Importance • Access modifiers helps to implement the concept of encapsulation in OOPs. • Encapsulation helps to hide the data and behavior. • Access Modifiers affect the accessibility at two levels : • Class • Members(methods and instance variables)
  • 5. Access Modifiers – at class level
  • 6. public • When a class is marked as public, it is visible to all other classes which are inside and outside the package. – Visible to everyone.. package com.java9s.Engines; package com.java9s.cars; import com.java9s.Engines.Engine; public class Engine{ public int engine1000cc(){ public class Ford{ int rpmCount=…..; void moveFast(){ return rpmCount; Engine e = new Engine(); } int rpm = e.engine3000cc() public int engine3000cc(){ //move with speed related to int rpmCount=…..; //rpm return rpmCount; } } } }
  • 7. public - class level • A class marked as public is be accessible to all classes in other packages, but should mention the import statement. • There is no need for an import statement when a class inside the same package uses the class marked as public
  • 8. default – class level • Default access has no key word. • When there is no access modifier declared, the access is default level access. • The classes marked with default access are visible only to the classes inside the same package.
  • 9. default – class level package com.java9s.bank; class InterestRates{ When there is no double creditCardInterest(){ access modifier specified …….; - The access is default level } double homeLoanInterest(){ ……; } package com.java9s.bank; } public class customerBanking{ double calculateHomeLoan(){ InterestRates i = new InterestRates(); double interest = i.creditCardInterest(); //calculate the home loan of customer return x; } }
  • 10. default – class level package com.java9s.bank; class InterestRates{ double creditCardInterest(){ …….; } double homeLoadInterest(){ ……; } package com.java9s.Customerbank; } public class customerBanking{ double calculateHomeLoan(){ InterestRates i = new InterestRates(); The accessing class is not double interest = i.creditCardInterest(); in the same package. So, the class //calculate the home loan of customer With default will not be visible return x; } }
  • 11. protected and private – class level ***protected and private access modifiers are not applicable to the class level declaration***
  • 12. Access modifiers – member level (methods and instance variables)
  • 13. public – member level • A member with public access is visible to all the classes inside and outside package. • The class in which the member exists should be is visible to the accessing class.
  • 14. public – member level package com.java9s.Engines; package com.java9s.cars; import com.java9s.Engines.Engine; public class Engine{ public int engine1000cc(){ public class Ford{ int rpmCount=…..; void moveFast(){ return rpmCount; Engine e = new Engine(); } int rpm = e.engine3000cc() public int engine3000cc(){ //move with speed related to int rpmCount=…..; //rpm return rpmCount; } } } } •Check if the class itself is accessible •Check if the import statement is used to import the class(if accessed from other package) •Finally- check if the member is accessible
  • 15. public – member level package com.java9s.Engines; package com.java9s.cars; import com.java9s.Engines.Engine; class Engine{ public int engine1000cc(){ public class Ford{ int rpmCount=…..; void moveFast(){ return rpmCount; Engine e = new Engine(); } int rpm = e.engine3000cc() public int engine3000cc(){ //move with speed related to int rpmCount=…..; //rpm return rpmCount; } } } } The class engine is having default access and will not be visible to Ford
  • 16. default – member level • A member marked with default access will be visible to the classes that are in the same package.
  • 17. default – member level package com.java9s.bank; class InterestRates{ double creditCardInterest(){ …….; } double homeLoadInterest(){ ……; } package com.java9s.bank; } public class customerBanking{ double calculateHomeLoan(){ InterestRates i = new InterestRates(); double interest = i.creditCardInterest(); //calculate the home loan of customer return x; } }
  • 18. protected – member level • A member marked as protected is visible to all classes in the same package(Just like default). • protected members are also accessible to classes outside the package, but the accessing class should be a subclass of the member class.
  • 19. protected- member level package com.java9s.cars; package com.java9s.cars; public class Car{ public class Benz{ protected int speed; int move(){ } Car c = new Car(); package com.java9s.fastCars; return c.speed; public class Ferrari extends Car{ } int moveFast(){ return super.speed; } } int move(){ Note: The protected members can be Car c= new Car(); accessed only by the subclasses in other c.speed; packages and can invoke the members only through inheritance mode. } Not by creating an instance. }
  • 20. private – member level • When a member is marked as private, it is only visible to other members inside the same class. • Other classes inside and outside the package will not be able to access the private members of a class.
  • 21. private – member level public class Car{ private String keyCode; } public class Theif{ keyCode variable is not void steal(){ visible outside the class Car Car c = new Car(); c.keyCode; } }
  • 22. protected and private – class level ***protected and private access modifiers are not applicable to the class level declaration*** ???
  • 23. Access Modifiers - summary Visibility public protected default private From the same class Yes Yes Yes Yes From a class in same package Yes Yes Yes No From a class from outside the Yes No No No package From a subclass outside the Yes Yes(Only No No package through inheritance mode) From a subclass in the same Yes Yes Yes No package
  • 24. Access Modifiers – Local Variables public class Calculator{ public int addition(int a, int b){ int c = a+b; return c; C is a local variable and only lives till the method } Executes. } No access modifiers should be applied for Local variables
  • 25. Thank you Follow me on to get more updates on latest video posts Subscribe on http://www.youtube.com/user/java9s Twitter : @java9s facebook: www.facebook.com/java9s www.JAVA9S.com