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)

Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
Pooja Jaiswal
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
Shreyans Pathak
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Static Members-Java.pptx
Static Members-Java.pptxStatic Members-Java.pptx
Static Members-Java.pptx
ADDAGIRIVENKATARAVIC
 
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
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Abishek Purushothaman
 
Constructors and Destructor in C++
Constructors and Destructor in C++Constructors and Destructor in C++
Constructors and Destructor in C++
International Institute of Information Technology (I²IT)
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Method Overloading In Java
Method Overloading In JavaMethod Overloading In Java
Method Overloading In Java
CharthaGaglani
 
Inheritance ppt
Inheritance pptInheritance ppt
Inheritance ppt
Nivegeetha
 
Friend function
Friend functionFriend function
Friend function
zindadili
 
friend function(c++)
friend function(c++)friend function(c++)
friend function(c++)
Ritika Sharma
 
Function overloading ppt
Function overloading pptFunction overloading ppt
Function overloading ppt
Prof. Dr. K. Adisesha
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Access Protection
Access ProtectionAccess Protection
Access Protection
myrajendra
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Inheritance in java
Inheritance in java Inheritance in java
Inheritance in java
yash jain
 
Abstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core JavaAbstract Class & Abstract Method in Core Java
Abstract Class & Abstract Method in Core Java
MOHIT AGARWAL
 

Viewers also liked (19)

Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Sourabrata Mukherjee
 
12 java modifiers
12 java modifiers12 java modifiers
12 java modifiers
Federico Russo
 
Learn Java Part 10
Learn Java Part 10Learn Java Part 10
Learn Java Part 10
Gurpreet singh
 
Access specifier in java
Access specifier in javaAccess specifier in java
Access specifier in java
Kaml Sah
 
software project management Waterfall model
software project management Waterfall modelsoftware project management Waterfall model
software project management Waterfall model
REHMAT ULLAH
 
Bluetooth technology
Bluetooth technologyBluetooth technology
Bluetooth technology
Rohit Roy
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Bluetooth
BluetoothBluetooth
Bluetooth
Sumeet Rayat
 
Classical problem of synchronization
Classical problem of synchronizationClassical problem of synchronization
Classical problem of synchronization
Shakshi Ranawat
 
Visibility control in java
Visibility control in javaVisibility control in java
Visibility control in java
Tech_MX
 
Bluetooth - Overview
Bluetooth - OverviewBluetooth - Overview
Bluetooth - Overview
Shobana Pattabiraman
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
Muthukumaran Subramanian
 
Bluetooth wi fi wi max 2, 3
Bluetooth wi fi wi max 2, 3Bluetooth wi fi wi max 2, 3
Bluetooth wi fi wi max 2, 3
jandrewsxu
 
Awt
AwtAwt
Awt
Rakesh Patil
 
Wi-Fi vs Bluetooth
Wi-Fi vs BluetoothWi-Fi vs Bluetooth
Wi-Fi vs Bluetooth
Arun ACE
 
Waterfall Model
Waterfall ModelWaterfall Model
Waterfall Model
university of education,Lahore
 
Waterfall model ppt final
Waterfall model ppt  finalWaterfall model ppt  final
Waterfall model ppt final
shiva krishna
 
Waterfall model
Waterfall modelWaterfall model
Waterfall model
BHARGAV VISANI
 
Wi-Fi Technology
Wi-Fi TechnologyWi-Fi Technology
Wi-Fi Technology
Naveen Kumar
 

Similar to Java access modifiers (20)

Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
VishnuSupa
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
SudhanshuVijay3
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
karan saini
 
OOP
OOPOOP
OOP
karan saini
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
vanithaRamasamy
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
Sivakumar M
 
00ps inheritace using c++
00ps inheritace using c++00ps inheritace using c++
00ps inheritace using c++
sushamaGavarskar1
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Inheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsInheritance and Polymorphism in Oops
Inheritance and Polymorphism in Oops
LalfakawmaKh
 
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
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
Vinay Kumar
 
Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Shweta Shah
 
Inheritance
InheritanceInheritance
Inheritance
Pranali Chaudhari
 
11 Inheritance.ppt
11 Inheritance.ppt11 Inheritance.ppt
11 Inheritance.ppt
LadallaRajKumar
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
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
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 
Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
Sandeep Chawla
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
VishnuSupa
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
Sivakumar M
 
Inheritance and Polymorphism in Oops
Inheritance and Polymorphism in OopsInheritance and Polymorphism in Oops
Inheritance and Polymorphism in Oops
LalfakawmaKh
 
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
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
Vinay Kumar
 
Inheritance
InheritanceInheritance
Inheritance
Tech_MX
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
Shweta Shah
 
Inheritance in C++
Inheritance in C++Inheritance in C++
Inheritance in C++
RAJ KUMAR
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
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
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
Vishal Patil
 

Recently uploaded (20)

Deno ...................................
Deno ...................................Deno ...................................
Deno ...................................
Robert MacLean
 
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & TipsTrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc
 
Gojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptxGojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptx
V3cube
 
The Future of Repair: Transparent and Incremental by Botond Dénes
The Future of Repair: Transparent and Incremental by Botond DénesThe Future of Repair: Transparent and Incremental by Botond Dénes
The Future of Repair: Transparent and Incremental by Botond Dénes
ScyllaDB
 
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIATHE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
Srivaanchi Nathan
 
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
 
Computational Photography: How Technology is Changing Way We Capture the World
Computational Photography: How Technology is Changing Way We Capture the WorldComputational Photography: How Technology is Changing Way We Capture the World
Computational Photography: How Technology is Changing Way We Capture the World
HusseinMalikMammadli
 
Build with AI on Google Cloud Session #4
Build with AI on Google Cloud Session #4Build with AI on Google Cloud Session #4
Build with AI on Google Cloud Session #4
Margaret Maynard-Reid
 
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-StoryRevolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
ssuser52ad5e
 
Endpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore ItEndpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore It
MSP360
 
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar PatturajInside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
ScyllaDB
 
Future-Proof Your Career with AI Options
Future-Proof Your  Career with AI OptionsFuture-Proof Your  Career with AI Options
Future-Proof Your Career with AI Options
DianaGray10
 
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
 
L01 Introduction to Nanoindentation - What is hardness
L01 Introduction to Nanoindentation - What is hardnessL01 Introduction to Nanoindentation - What is hardness
L01 Introduction to Nanoindentation - What is hardness
RostislavDaniel
 
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
Safe Software
 
Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)
nick896721
 
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
maharajput103
 
UiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and OpportunitiesUiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and Opportunities
DianaGray10
 
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial PresentationMIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND CTI
 
EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
 
Deno ...................................
Deno ...................................Deno ...................................
Deno ...................................
Robert MacLean
 
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & TipsTrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc Webinar - Building your DPIA/PIA Program: Best Practices & Tips
TrustArc
 
Gojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptxGojek Clone Multi-Service Super App.pptx
Gojek Clone Multi-Service Super App.pptx
V3cube
 
The Future of Repair: Transparent and Incremental by Botond Dénes
The Future of Repair: Transparent and Incremental by Botond DénesThe Future of Repair: Transparent and Incremental by Botond Dénes
The Future of Repair: Transparent and Incremental by Botond Dénes
ScyllaDB
 
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIATHE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
THE BIG TEN BIOPHARMACEUTICAL MNCs: GLOBAL CAPABILITY CENTERS IN INDIA
Srivaanchi Nathan
 
BoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is DynamicBoxLang JVM Language : The Future is Dynamic
BoxLang JVM Language : The Future is Dynamic
Ortus Solutions, Corp
 
Computational Photography: How Technology is Changing Way We Capture the World
Computational Photography: How Technology is Changing Way We Capture the WorldComputational Photography: How Technology is Changing Way We Capture the World
Computational Photography: How Technology is Changing Way We Capture the World
HusseinMalikMammadli
 
Build with AI on Google Cloud Session #4
Build with AI on Google Cloud Session #4Build with AI on Google Cloud Session #4
Build with AI on Google Cloud Session #4
Margaret Maynard-Reid
 
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-StoryRevolutionizing-Government-Communication-The-OSWAN-Success-Story
Revolutionizing-Government-Communication-The-OSWAN-Success-Story
ssuser52ad5e
 
Endpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore ItEndpoint Backup: 3 Reasons MSPs Ignore It
Endpoint Backup: 3 Reasons MSPs Ignore It
MSP360
 
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar PatturajInside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
Inside Freshworks' Migration from Cassandra to ScyllaDB by Premkumar Patturaj
ScyllaDB
 
Future-Proof Your Career with AI Options
Future-Proof Your  Career with AI OptionsFuture-Proof Your  Career with AI Options
Future-Proof Your Career with AI Options
DianaGray10
 
Fl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free DownloadFl studio crack version 12.9 Free Download
Fl studio crack version 12.9 Free Download
kherorpacca127
 
L01 Introduction to Nanoindentation - What is hardness
L01 Introduction to Nanoindentation - What is hardnessL01 Introduction to Nanoindentation - What is hardness
L01 Introduction to Nanoindentation - What is hardness
RostislavDaniel
 
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
[Webinar] Scaling Made Simple: Getting Started with No-Code Web Apps
Safe Software
 
Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)Early Adopter's Guide to AI Moderation (Preview)
Early Adopter's Guide to AI Moderation (Preview)
nick896721
 
Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025Wondershare Dr.Fone Crack Free Download 2025
Wondershare Dr.Fone Crack Free Download 2025
maharajput103
 
UiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and OpportunitiesUiPath Agentic Automation Capabilities and Opportunities
UiPath Agentic Automation Capabilities and Opportunities
DianaGray10
 
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial PresentationMIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND Revenue Release Quarter 4 2024 - Finacial Presentation
MIND CTI
 
EaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial KeyEaseUS Partition Master Crack 2025 + Serial Key
EaseUS Partition Master Crack 2025 + Serial Key
kherorpacca127
 

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