7.access Specifiers and Methods in Java
7.access Specifiers and Methods in Java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
❑ Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
❑ Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
❑ Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
• // Calculator.java
• public class Calculator {
• // Public method to add two numbers
• public int add(int a, int b) {
• return a + b;
• }
•}
• // TestCalculator.java
• public class TestCalculator {
• public static void main(String[] args) {
• Calculator calc = new Calculator();
• int result = calc.add(5, 3); // Accessing the
public method
• System.out.println("The sum is: " +
result);
• }
• }
PRIVATE Simple example of private
class A{ access modifier
private int data=40; In this example, we have
private void msg() created two classes A and
{ Simple. A class contains
System.out.println("Hello java");}
private data member and
}
private method. We are
public class Simple{
accessing these private
public static void main(String args[]){
members from outside the
A obj=new A();
System.out.println(obj.data);//Compile Time Error
class, so there is a compile-
obj.msg();//Compile Time Error time error.
}
}
DEFAULT If you don't use any modifier, it is treated
as default by default. The default modifier is
//save by A.java accessible only within package. It cannot be
accessed from outside the package. It
package pack; provides more accessibility than private. But,
class A{
it is more restrictive than protected, and
public.
void msg(){System.out.println("Hello");
}
Example of default access modifier
//save by B.java
In this example, we have created two packages pack
package mypack;
and mypack. We are accessing the A class from
import pack.*;
outside its package, since A class is not public, so it
class B{ cannot be accessed from outside the package.
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
3) Protected
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
❖ Predefined Method
❖ User-defined Method
•Predefined
Method
• Predefined Method
• In Java, predefined methods are
the method that is already
defined in the Java class
libraries is known as predefined
methods. It is also known as the
standard library method or built-
in method. We can directly use
these methods just by calling
them in the program at any
point. Some pre-defined methods
are length(), equals(),
compareTo(), sqrt(), etc. When
we call any of the predefined
methods in our program, a series
of codes related to the
corresponding method runs in
the background that is already
stored in the library.
Demo.java
In the above example, we have used three predefined methods main(), print(),
and max(). We have used these methods directly without declaration because
they are predefined. The print() method is a method of PrintStream class that
prints the result on the console. The max() method is a method of the Math
class that returns the greater of two numbers.
1. Object Class
equals(Object obj): Determines whether two objects are equal.
hashCode(): Returns a hash code value for the object.
toString(): Returns a string representation of the object.
getClass(): Gets the runtime class of an object.
clone(): Creates and returns a copy of this object.
String Class
charAt(int index): Returns the character at the specified index.
indexOf(String str): Returns the index within the string of the first occurrence of the
specified substring.
split(String regex):
trim(): Returns Splits
a copy thestring,
of the string with
around matches
leading andof the given
trailing regular omitted.
whitespace expression
• Math Class (Static Methods)
• sqrt(double a): Returns the square root of
a value.
• pow(double a, double b): Returns the
value of the first parameter raised to the
power of the second parameter.
• abs(int a): Returns the absolute value of
an integer.
• max(int a, int b): Returns the greater of
two int values.
• min(int a, int b): Returns the smaller of
two int values.
• round(double a): Rounds a double value
to the nearest whole number.
• Arrays Class (Static Methods)
• sort(int[] a): Sorts the specified array of
ints into ascending numerical order.
• binarySearch(int[] a, int key): Searches the
specified array for the specified value using
the binary search algorithm.
• copyOf(T[] original, int newLength):
Copies the specified array, truncating or
padding with nulls (if necessary) so the copy
has the specified length.
• equals(int[] a, int[] a2): Returns true if the
two specified arrays of ints are equal to one
another.
• fill(int[] a, int val): Assigns the specified
int value to each element of the specified
array of ints.
• Collections Framework
• add(E e), remove(Object o), size(),
isEmpty(): Basic operations provided by
Collection interface implementations
like ArrayList, HashSet, etc.
• binarySearch(List<? extends
Comparable<? super T>> list, T key):
Searches the specified list for the
specified object using the binary search
algorithm.
• User-defined Method
• The method written by the user or programmer is known as
a user-defined method. These methods are modified according
to the requirement.
Instance
method
Abstract
method
Static
method
Instance
method
Abstract
method
Static Methods
Static methods belong to the class rather than a specific instance of the class.
This means that they can be called without creating an object of the class.
Static methods are used for operations that don't require any data from an
instance of the class (object).
Syntax:
public static returnType methodName(parameters)
{
// body
}
Example: Checking if a number is even
Instance
method
Abstract
method
Static
method
Instance
method
Abstract
method
2. Instance Methods
Instance methods belong to an instance of a class. To use an
instance method, you must first create an object of the class.
These methods can access instance variables and other instance
methods directly.
Syntax:
public returnType methodName(parameters)
{
// body
}
Example 1: Updating and displaying the balance of a bank account
Instance
method
Abstract
method
Static
method
Instance
method
Abstract
method
3. Abstract Methods
Abstract methods are methods that are declared without an
implementation. If a class includes an abstract method, then the class
itself must be declared abstract. Abstract methods are used to specify that
the subclasses must provide implementations for these methods.
Syntax: