SlideShare a Scribd company logo
1 of 28
Objectives



On completion of this period, you would be
able to learn
• Access protection
• Access modifiers
• Applying access protection




                                             1
Recap

Packages
• Name provide to a group of classes
• A collection of related classes and interfaces
• A name space management tool provided by
  Java




                                                   2
Access Protection
• What is access protection
  • In objects, certain members have to be
    protected from unauthorized access
  • In C++, we learnt how to do such
    protection
  • We used private, public, and protected
    keywords for this purpose
  • Java also has such features


                                             3
Access Protection
• Access Protection
  • To protect the access of members of an
    object
  • Done with the help of access modifiers
  • Keywords are – private, public and
    protected
  • Access modifiers are also known as
    Visibility Modifiers


                                             4
Access Protection
• Purpose of Access Protection
  • Enforces
     • information hiding
     • encapsulation




                                  5
Access Modifiers
• Types of Access Modifiers
 • public
 • private
 • protected
 • default (no special keyword)




                                  6
Access Modifiers        Contd..
• public access
   • Member is visible or accessible to the world
   • Any method of any object can use a public
     member
   • keyword : public
   • eg. : public int number;
   •        public void sum(){
   •                …                      Put before
                                           return type
   •        }
   • Generally access methods are public
                                                         7
Access Modifiers Contd..
• private access
   • Member is visible or accessible only within its
     own class
   • Members cannot be inherited by subclasses
   • Members cannot be accessible in subclasses
   • Keyword : private




                                                       8
Access Modifiers Contd..
• private access
   • eg. : private double average;
   •        private void debug (String msg) {
   •                 …
   •         }
   • Provides the highest degree of protection




                                                 9
Access Modifiers       Contd..
• protected access
   • Member is visible or accessible to
      • The current class
      • Subclasses of the current class
      • All classes that are in the same package as
        that of the class
   • Keyword : protected
   • eg. : protected String message Str;
   • The level of protection is between public
     access and default access
                                                  10
Access Modifiers       Contd..
• default access or package access
   • Members are accessible to
      • All the classes in the same package
      • No special keyword is used
   eg. : int length;




                                              11
Access Modifiers              Contd..




   Table 27.1: Class Member Accessibility


                                            12
Rules of thumb
• public : if the member to be visible
  everywhere
• protected : if the member is visible in the
  current package and also subclasses in
  other packages
• default : if the member to be visible in the
  current package
• private : if the member is to be used only
  within the class

                                                 13
Example
• Consider the access modifier
  for a member x in class A. If it
  is:
   • private – it can only be
      used inside A.
   • default – it can be used
      anywhere in package1,
      that is, A,B and C.
   • protected – it can be used
      anywhere in package1,
      and in subclasses of A in
      other packages, here S.
   • public – it can be used
      everywhere in the system                                       14
                                  Fig. 27.1. Packages with its classes
Example      Contd..
• Consider the access
  modifier for the class
  B. If it is:
  • default – the class
     can only be used in
     package1.
  • public – the class
     can be used from
     anywhere.

                            Fig. 27.2. Packages with its classes
                                                              15
Using Access Modifiers
• Guidelines :
  • Make all data members private
  • Create public getter and setter methods for data
    members as necessary
  • If possible, make a method private, else make it
    default, or make it public




                                                  16
Example Program
• With the help of the following program, we
  will try to analyze the access protection
  features




                                               17
Example Program
• Consider the Person class

• What access modifiers should be used, and
  which access should define?




                                              18
Example Program
public class Person {
  int SSNumber;
  String name;
  String address;
}




                              19
Example Program             Contd..
public class Person {
  private final int SSNumber;
  private String name;
  private String address;
  public Person(int ssn, String name) {
       SSNumber = ssn;
       this. name = name;
  }
  public String getName() {
       return name;
}
                                             20
Example Program            Contd..
public String getAddress () {
       return address;
  }
public void setAddress (String address) {
  this. address = address;
  }
}




                                            21
• The analysis is as follows
           Example Program           Contd..
  • The SSNumber* must be given when the person object
    is created, and cannot be changed later
  • The Name must be given when the object is created
    Normally it will not change later
  • The address need not be present, but it can be changed
    along the way




                                                        22
Summary
• In this class we have discussed
   • Access protection
   • Access modifiers
      • public, private, protected
   • How to use access modifiers




                                     23
Frequently Asked Questions
1. List the access modifiers in Java ?

2. What is the difference between default and
   protected modifiers ?

3. Explain how to use access modifiers




                                                24
Quiz

1. We would like to make a member of a class
  visible In all subclasses regardless of what
  package they are in. Which keyword is useful
  for that ?
   1. private
   2. public
   3. protected
   4. No keyword (default)




                    CM604.27                 25
Quiz             Contd..



2. Which keyword can make a class visible
  within a package?

  •   private
  •   public
  •   protected
  •   No keyword (default)




                    CM604.27                   26
Quiz              Contd..




3. Which keyword is useful for implementing
  information hiding principle?
   1. private
   2. public
   3. protected
   4. No keyword (default)




                    CM604.27                    27
Quiz              Contd..



4. Which one of the following is NOT a keyword
  related to Access protection?

  1. private
  2. public
  3. protected
  4. default




                    CM604.27                     28

More Related Content

What's hot (20)

Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
constructors in java ppt
constructors in java pptconstructors in java ppt
constructors in java ppt
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Dynamic storage allocation techniques
Dynamic storage allocation techniquesDynamic storage allocation techniques
Dynamic storage allocation techniques
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Java Methods
Java MethodsJava Methods
Java Methods
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Operators and Expressions in Java
Operators and Expressions in JavaOperators and Expressions in Java
Operators and Expressions in Java
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
C# Access modifiers
C# Access modifiersC# Access modifiers
C# Access modifiers
 
Java program structure
Java program structureJava program structure
Java program structure
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Concepts of oops
Concepts of oopsConcepts of oops
Concepts of oops
 
Friend function in c++
Friend function in c++Friend function in c++
Friend function in c++
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 

Viewers also liked

How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in javaTyagi2636
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eGina Bullock
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfacesİbrahim Kürce
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.netNeelesh Shukla
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception Handling
Exception HandlingException Handling
Exception HandlingReddhi Basu
 

Viewers also liked (20)

How would you implement multiple inheritance in java
How would you implement multiple inheritance in javaHow would you implement multiple inheritance in java
How would you implement multiple inheritance in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Java packages
Java packagesJava packages
Java packages
 
Eo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5eEo gaddis java_chapter_03_5e
Eo gaddis java_chapter_03_5e
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception
Java exception Java exception
Java exception
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

Similar to Access Modifiers

Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingArslan Waseem
 
Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulationNurhanna Aziz
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptxMDRakibKhan3
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxDaveEstonilo
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoopVladislav Hadzhiyski
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in javaAshwin Thadani
 
Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfsanjeevtandonsre
 
Java modifiers
Java modifiersJava modifiers
Java modifiersSoba Arjun
 
Inheritance,constructor,friend function
Inheritance,constructor,friend functionInheritance,constructor,friend function
Inheritance,constructor,friend functionFAKRUL ISLAM
 
How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#LearningTech
 
Access modifiers
Access modifiersAccess modifiers
Access modifiersJadavsejal
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesVinay Kumar
 
Access specifier
Access specifierAccess specifier
Access specifierzindadili
 

Similar to Access Modifiers (20)

27c
27c27c
27c
 
27csharp
27csharp27csharp
27csharp
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Oops (inheritance&interface)
Oops (inheritance&interface)Oops (inheritance&interface)
Oops (inheritance&interface)
 
Chapter 03 enscapsulation
Chapter 03 enscapsulationChapter 03 enscapsulation
Chapter 03 enscapsulation
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Access Modifiers .pptx
Access Modifiers .pptxAccess Modifiers .pptx
Access Modifiers .pptx
 
Object oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptxObject oriented programming CLASSES-AND-OBJECTS.pptx
Object oriented programming CLASSES-AND-OBJECTS.pptx
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
Access modifiers in java
Access modifiers in javaAccess modifiers in java
Access modifiers in java
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Access Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdfAccess Modifiers To set the access levels of variables,methods (mem.pdf
Access Modifiers To set the access levels of variables,methods (mem.pdf
 
Java modifiers
Java modifiersJava modifiers
Java modifiers
 
Encapsulation
EncapsulationEncapsulation
Encapsulation
 
Inheritance,constructor,friend function
Inheritance,constructor,friend functionInheritance,constructor,friend function
Inheritance,constructor,friend function
 
How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#How totestinternalprotectmethodsinc#
How totestinternalprotectmethodsinc#
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Access modifiers
Access modifiersAccess modifiers
Access modifiers
 
Access controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modesAccess controlaspecifier and visibilty modes
Access controlaspecifier and visibilty modes
 
Access specifier
Access specifierAccess specifier
Access specifier
 

More from myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
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
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 

Recently uploaded (20)

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
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
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 

Access Modifiers

  • 1. Objectives On completion of this period, you would be able to learn • Access protection • Access modifiers • Applying access protection 1
  • 2. Recap Packages • Name provide to a group of classes • A collection of related classes and interfaces • A name space management tool provided by Java 2
  • 3. Access Protection • What is access protection • In objects, certain members have to be protected from unauthorized access • In C++, we learnt how to do such protection • We used private, public, and protected keywords for this purpose • Java also has such features 3
  • 4. Access Protection • Access Protection • To protect the access of members of an object • Done with the help of access modifiers • Keywords are – private, public and protected • Access modifiers are also known as Visibility Modifiers 4
  • 5. Access Protection • Purpose of Access Protection • Enforces • information hiding • encapsulation 5
  • 6. Access Modifiers • Types of Access Modifiers • public • private • protected • default (no special keyword) 6
  • 7. Access Modifiers Contd.. • public access • Member is visible or accessible to the world • Any method of any object can use a public member • keyword : public • eg. : public int number; • public void sum(){ • … Put before return type • } • Generally access methods are public 7
  • 8. Access Modifiers Contd.. • private access • Member is visible or accessible only within its own class • Members cannot be inherited by subclasses • Members cannot be accessible in subclasses • Keyword : private 8
  • 9. Access Modifiers Contd.. • private access • eg. : private double average; • private void debug (String msg) { • … • } • Provides the highest degree of protection 9
  • 10. Access Modifiers Contd.. • protected access • Member is visible or accessible to • The current class • Subclasses of the current class • All classes that are in the same package as that of the class • Keyword : protected • eg. : protected String message Str; • The level of protection is between public access and default access 10
  • 11. Access Modifiers Contd.. • default access or package access • Members are accessible to • All the classes in the same package • No special keyword is used eg. : int length; 11
  • 12. Access Modifiers Contd.. Table 27.1: Class Member Accessibility 12
  • 13. Rules of thumb • public : if the member to be visible everywhere • protected : if the member is visible in the current package and also subclasses in other packages • default : if the member to be visible in the current package • private : if the member is to be used only within the class 13
  • 14. Example • Consider the access modifier for a member x in class A. If it is: • private – it can only be used inside A. • default – it can be used anywhere in package1, that is, A,B and C. • protected – it can be used anywhere in package1, and in subclasses of A in other packages, here S. • public – it can be used everywhere in the system 14 Fig. 27.1. Packages with its classes
  • 15. Example Contd.. • Consider the access modifier for the class B. If it is: • default – the class can only be used in package1. • public – the class can be used from anywhere. Fig. 27.2. Packages with its classes 15
  • 16. Using Access Modifiers • Guidelines : • Make all data members private • Create public getter and setter methods for data members as necessary • If possible, make a method private, else make it default, or make it public 16
  • 17. Example Program • With the help of the following program, we will try to analyze the access protection features 17
  • 18. Example Program • Consider the Person class • What access modifiers should be used, and which access should define? 18
  • 19. Example Program public class Person { int SSNumber; String name; String address; } 19
  • 20. Example Program Contd.. public class Person { private final int SSNumber; private String name; private String address; public Person(int ssn, String name) { SSNumber = ssn; this. name = name; } public String getName() { return name; } 20
  • 21. Example Program Contd.. public String getAddress () { return address; } public void setAddress (String address) { this. address = address; } } 21
  • 22. • The analysis is as follows Example Program Contd.. • The SSNumber* must be given when the person object is created, and cannot be changed later • The Name must be given when the object is created Normally it will not change later • The address need not be present, but it can be changed along the way 22
  • 23. Summary • In this class we have discussed • Access protection • Access modifiers • public, private, protected • How to use access modifiers 23
  • 24. Frequently Asked Questions 1. List the access modifiers in Java ? 2. What is the difference between default and protected modifiers ? 3. Explain how to use access modifiers 24
  • 25. Quiz 1. We would like to make a member of a class visible In all subclasses regardless of what package they are in. Which keyword is useful for that ? 1. private 2. public 3. protected 4. No keyword (default) CM604.27 25
  • 26. Quiz Contd.. 2. Which keyword can make a class visible within a package? • private • public • protected • No keyword (default) CM604.27 26
  • 27. Quiz Contd.. 3. Which keyword is useful for implementing information hiding principle? 1. private 2. public 3. protected 4. No keyword (default) CM604.27 27
  • 28. Quiz Contd.. 4. Which one of the following is NOT a keyword related to Access protection? 1. private 2. public 3. protected 4. default CM604.27 28