Access Modifier in Java with Example

Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer. 

Welcome back to Java Tutorials, with an excitement to move one more step in Java learning. Today I am sharing in this blogpost/tutorials about Java Access Modifiers.

Access modifier (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation (Packing the data and function into single components/ Hiding the data member and member functions) of components.

Types of Access Modifiers:

  • Access Control Modifiers
  • Non Access Modifiers

Access Control Modifiers: Java has a capability to access the control of/regulate the: classes, variable, methods, constructor, subclass, packages and interface using below four keywords in a definition and change their meaning. It also helps the program to have a structure proper scoping of a method/function and variables declared by a Coders.

Order of Access Control specifiers: Most to Least order of Access Control Specifiers.

Public > Protected > Default (Package Private)> Private

 

There are four types of Access Control Modifiers:

  1. Default : When no modifier is used then member variables and methods are accessible in same class or in any other class in same package.
  2. Public : Accessible to any class where ever it is inherited or imported
  3. Protected : Accessible in same package and also in subclass in some other package
  4. Private:  Accessible only in class

Default Access Control Modifiers:
Default Access Control Modifiers have the access control/Scoping will be visible only to code inside the class as well as in the same package

In Brief : Default access Modifier can also be called as private to the package level, can access class, inner class , member variables, methods/member functions, constructor for which the default access is assigned to. Note: Constructor will be visible to only the same package.

Example:

Now we are going to create two package one is pack1 and second with name pack2. Here we are going to create one class Employee.java in package pack1 without any modifier from private, public or protected.

Now we are going to create second class “TestDefaultAccessModifierAsPackagePrivate.java” and we are going to create a object of Employee.

Here going to post one snap taken from eclipse.
default modifierAbove compilation error stating to “Change visibility of Employee to ‘public'” . It shows that Employee class can not be accessed outside the same package. In the same fashion Subclass(Suppose ChildEmployee.java) can not access the member variable and member function of Employee class if this SubClass is in some other package.
Note:
1- While Subclass in same package can access all the member variable and method from the SuperClass.

2- In interface default modifier is counted as public.In interface the member variable are implicitly public static final and methods in interface are default by final; modifiers other than public are forbidden in Interface.

3- Enumeration constants are always public.

Protected Access Control Specifiers: Protected Access Control specifiers is similar as default except one difference, it allows sub- class (Inside & outside the packages) to inherit the member variables, member function, and constructors outside the same package.

**Protected Access Control specifiers applies only to inheritance.

Explanation: If a subclass outside the package has a reference to an instance of the superclass, the subclass can’t access the protected method using that superclass references. The only way subclass can access that method is by inheriting it or we can say the subclass outside the package doesn’t have access to the protected method. It just has the method, through inheritance

Protected Access Control specifiers are not applied to class and interfaces. Method and member variables can be declared as protected access control specifiers, however using Interface method and member variables are not declared as protected access control specifiers.Protected Access control specifiers give the subclass give a chance to use helper method and variable

** Inheritance – “public class Father extends Grandfather” using extend keyword we are inheriting the property of grandfather in father class, which cannot be reference variable.

An Interesting example of protected access specifier:
We are going to create a public class Base in package pack1 with protected method

Now we are going to create another public class Derived in package pack2 and will discuss the complexity.

Now the question arises why this compilation error. Because new Base().display(); is not direct inheritance and a protected method can only be access by object of same package and since instance is being created in another package so Protected method can not be accessed.

Above code will work if we are going to call the method directly like this

Second way of using the protected method in Derived Class is to call the instance of Derived class to access the protected method of its Superclass Base. So here is the example

 

Now lets move ahead with another example to see the protected access modifier.

Lets create there classes GrandFather in package pack1, Father class in pack2 package and Son class in package pack3 and please don’t add any code first just create empty classes with public access modifier.

Now add one protected method foo in GrandFather class like this

So let see the three scenario in which this foo method could be called

Scenario 1: Accessing foo method by a class in same package pack1 lets say class name is SomeClass with instance of its subclass

Here you will see no error and method can be accessed successfully.

Scenario 2: Accessing foo protected method using the same instance of subclass. Here again this method would be accessed successfully.
See the example

In above example this keyword has been used to access the foo method that is protected in GrandFather class.

Same thing is also true with Son class see the example:

Scenario 3: Access the protected method foo using GrandFather instance in subclass and this will throw exception since instance of GrandFather Class is not in same package. So see the example
Example 1:  For Father Class

For Son Class:

Note:
Marking constructor as protected will be giving a compile time error & protected access gives the subclass a chance to use the helper method or variable, while preventing a non related class from trying to use it.

Private Access specifier: Private access specifier have limited access to class only where we can achieve encapsulation or hide unimportant data from the world. Method, variable & constructors that are declared private can be access within the same class only.

Class should not be declared as private, however we generally don’t apply private access specifier on class as well as constructor because that seems of not re-usability. In case of non-static method you can access directly because of this reference, even in below example of constructors but access using static method we have to create an object of the class

** Exception: Static method are not inherited in java, it will create a separate copy and static are related to class not the state of the object

Exception: Variables that are declared private can be accessed outside the class if public getter methods are present in the class. Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members’ class.

Lets create one class Example with few of its constructor as private.In this we will see that private constructor can be accessed in same class.

In above code, Both constructor are defined private but instance are created since both are in same class.

Lets create another class ExampleTest and lets see what happened

So it proves that private constructor can not be accessed out side the class.

Public Access Modifier:  Public is accessible from anywhere and have widest scope from all the specifiers. A class, method, constructor, interface etc. declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.

Different Packages: However if the public class we are trying to access is in a different package, then the public class still need to be imported.

Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. If the public class we are trying to access is in a different package, then the public class still need to be imported.

Thumb rules:

 

  • Methods declared public in a superclass also must be public in all subclasses.
  • Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private.
  • Methods declared without access control (no modifier was used) can be declared more private in subclasses.
  • Methods declared private are not inherited at all, so there is no rule for them.

Learn String operations in Java using examples

In the previous article, we discussed about String class in Java. We learnt the ways a String object can be constructed. We also figured out the difference between String and StringBuffer. We discussed 2 string methods length() and Intern() as well. I hope that article would have been helped you in the endeavors learning Strings in Java.

 

In continuation here we will talk about some more string operation (mostly useful for automation testing practice) through which String can be manipulated in the many ways according to the need. In automation testing we face many situations where it is required to manipulate the string.

  1. Concatenating String: In Java, two or more string objects can be concatenated in 2 ways as below:
    1. Using + operator: Please take a look in the below program:


       

      //another example

       

    2. Using concat() method:Please refer to below example:

       

  2. CharAt: This method helps us to find the character at the given index of the String. The index starts from 0 i.e. the first character of the string is at the 0th index. The last character is at the length() – 1 index.(Syntax: public char charAt(int index) )

     

  3. compareTo: This method is used to compare the two strings lexicographically. It returns int value as the comparison result.
    Value ‘0’ is returned if both the strings are equal. Value less than ‘0’ is returned if the argument string is greater than this string. Value greater than ‘0’ is returned if argument string is less than this string.

    CompareTo method can also be used to compare any 2 objects as this method is part of Java object class. So it is not limited to String comparisons only.

  4. ContentEquals: This method compares String with StringBuffer and returns Boolean value.

     

     

  5. Equals and equalsIgnoreCase: To compare two strings for equality, use equals( ). It has this general form:

    Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive. To perform a comparison that ignores case differences, call equalsIgnoreCase().

    When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:

    Here, str is the String object being compared with the invoking String object. It, too, returns true if the strings contain the same characters in the same order, and false otherwise.
    Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):

    The output from the program is shown here:

  6. getChars: If you need to extract more than one character at a time, you can use the getChars( ) method. It has this general form:

    Here is the output of this program:

     

     

  7. replace: The replace( ) method replaces all occurrences of one character in the invoking string with another character. It has the following general form:

    Here, original specifies the character to be replaced by the character specified by replacement. The resulting string is returned. For example,

    puts the string “Hewwo” into s.

  8. split:  Ahhh!! I just love this method. Ihave built framework around this function only.
    You can split a String using this method. String is broken around the given delimiter(regular expression). It returns an array of Strings. Let’s understand by an example:

    Here is the output of this program:

    Number of splited Strings can also be controlled by using the overloaded method of Split 

    output:

     

     

  9. substring: You can extract a substring using substring( ). It has two forms. The first is

    Here, startIndex specifies the index at which the substring will begin. This form returns a copy of the substring that begins at startIndex and runs to the end of the invoking string. The second form of substring( ) allows you to specify both the beginning and ending index of the substring:

    Here, startIndex specifies the beginning index, and endIndex specifies the stopping point. The string returned contains all the characters from the beginning index, up to, but not including, the ending index.

    output:

     

  10.  toUppercase and toLowerCase: These 2 methods are used to convert the questioned string to all upper case letters and lower case letters respectively.

     

     

  11. Trim: If there is situation where you have the string which has spaces in its starting and in ending, this method will help you out to remove those.

1 2 3 59