0% found this document useful (0 votes)
24 views

Access Modifiers Lect 4

The document discusses Java access modifiers which are used to control the visibility and accessibility of classes, variables, methods and other members. There are four main access modifiers in Java - default, private, protected, and public. The document explains what each access modifier means and provides examples of how they control the scope of accessible members. It also discusses how the 'this' keyword is used to refer to the current object and resolve ambiguity when a parameter and instance variable have the same name.

Uploaded by

Onyango Bernard
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Access Modifiers Lect 4

The document discusses Java access modifiers which are used to control the visibility and accessibility of classes, variables, methods and other members. There are four main access modifiers in Java - default, private, protected, and public. The document explains what each access modifier means and provides examples of how they control the scope of accessible members. It also discusses how the 'this' keyword is used to refer to the current object and resolve ambiguity when a parameter and instance variable have the same name.

Uploaded by

Onyango Bernard
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Java Access Modifiers

What are Access Modifiers?


In Java, access modifiers are used to set the accessibility (visibility) of classes, interfaces,
variables, methods, constructors, data members, and the setter methods. For exampl

class Animal {
public void method1() {...}

private void method2() {...}


}

In the above example, we have declared 2 methods: method1() and method2(). Here,

method1 is public - This means it can be accessed by other classes.


method2 is private - This means it can not be accessed by other classes.

Note the keyword public and private. These are access modifiers in Java. They are also known as visibility
modifiers.

There are four access modifiers keywords in Java and they are:

Modifier Description

Default declarations are visible only within the package (package private)

Private declarations are visible within the class only

Protected declarations are visible within the package or all subclasses

Public declarations are visible everywhere

Default Access Modifier

If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default the
default access modifier is considered. For example,

package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
}
}
Here, the Logger class has the default access modifier. And the class is visible to all the classes that
belong to the defaultPackage package. However, if we try to use the Logger class in another class outside
of defaultPackage, we will get a compilation error.

Private Access Modifier


When variables and methods are declared private, they cannot be accessed outside of the class. For
example,

class Data {
// private variable
private String name;
}

public class Main {


public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class


d.name = "Developer";
}
}
In the above example, we have declared a private variable named name. When we run the program, we
will get the following error:

Main.java:18: error: name has private access in Data


d.name = "Programiz";
^

The error is generated because we are trying to access the private variable of the Data class from the
Main class.

You might be wondering what if we need to access those private variables. In this case, we can use the
getters and setters method. For example,

class Data {
private String name;

// getter method
public String getName() {
return this.name;
}
// setter method
public void setName(String name) {
this.name= name;
}
}
public class Main {
public static void main(String[] main){
Data d = new Data();

// access the private variable using the getter and setter


d.setName("Programiz");
System.out.println(d.getName());
}
}
In the above example, we have a private variable named name. In order to access the variable from the
outer class, we have used methods: getName() and setName(). These methods are called getter and
setter in Java.

Here, we have used the setter method (setName()) to assign value to the variable and the getter method
(getName()) to access the variable.

We have used this keyword inside the setName() to refer to the variable of the class. To learn more on
this keyword

Protected Access Modifier


When methods and data members are declared protected, we can access them within the same package
as well as from subclasses. For example,

class Animal {
// protected method
protected void display() {
System.out.println("I am an animal");
}
}

class Dog extends Animal {


public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
dog.display();
}
}

In the above example, we have a protected method named display() inside the Animal class. The Animal
class is inherited by the Dog class. To learn more about inheritance, visit Java Inheritance.

We then created an object dog of the Dog class. Using the object we tried to access the protected
method of the parent class.
Since protected methods can be accessed from the child classes, we are able to access the method of
Animal class from the Dog class

Public Access Modifier


When methods, variables, classes, and so on are declared public, then we can access them from
anywhere. The public access modifier has no scope restriction. For example,

// Animal.java file
// public class
public class Animal {
// public variable
public int legCount;

// public method
public void display() {
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}

// Main.java
public class Main {
public static void main( String[] args ) {
// accessing the public class
Animal animal = new Animal();

// accessing the public variable


animal.legCount = 4;
// accessing the public method
animal.display();
}
}

Here,

The public class Animal is accessed from the Main class.


The public variable legCount is accessed from the Main class.
The public method display() is accessed from the Main class.

Access modifiers are mainly used for encapsulation. It can help us to control what part of a program can
access the members of a class. So that misuse of data can be prevented. To learn more about
encapsulation

this Keyword
this keyword is used to refer to the current object inside a method or a constructor. For
example,
class Main {
int instVar;

Main(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}
In the above example, we created an object named obj of the class Main. We then print the reference to
the object obj and this keyword of the class.

Here, we can see that the reference of both obj and this is the same. It means this is nothing but the
reference to the current object.

Use of this Keyword

There are various situations where this keyword is commonly used.

Using this for Ambiguity Variable Names

In Java, it is not allowed to declare two or more variables having the same name inside a scope (class
scope or method scope). However, instance variables and parameters may have the same name. For
example,

class MyClass {
// instance variable
int age;

// parameter
MyClass(int age){
age = age;
}
}

In the above program, the instance variable and the parameter have the same name: age. Here, the Java
compiler is confused due to name ambiguity.

In such a situation, we use this keyword. For example,


First, let's see an example without using this keyword:

class Main {
int age;
Main(int age){
age = age;
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}

In the above example, we have passed 8 as a value to the constructor. However, we are getting 0 as an
output. This is because the Java compiler gets confused because of the ambiguity in names between
instance the variable and the parameter.

Now, let's rewrite the above code using this keyword.

class Main {
int age;
Main(int age){
this.age = age;
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}
Now, we are getting the expected output. It is because when the constructor is called, this inside the
constructor is replaced by the object obj that has called the constructor. Hence the age variable is
assigned value 8.

Also, if the name of the parameter and instance variable is different, the compiler automatically appends
this keyword. For example, the code:

class Main {
int age;

Main(int i) {
age = i;
}
}
is equivalent to:

class Main {
int age;
Main(int i) {
this.age = i;
}
}

this with Getters and Setters


Another common use of this keyword is in setters and getters methods of a class. For example:

class Main {
String name;

// setter method
void setName( String name ) {
this.name = name;
}

// getter method
String getName(){
return this.name;
}

public static void main( String[] args ) {


Main obj = new Main();

// calling the setter and the getter method


obj.setName("Toshiba");
System.out.println("obj.name: "+obj.getName());
}
}
Here, we have used this keyword:

to assign value inside the setter method

to access value inside the getter method

Using this in Constructor Overloading

While working with constructor overloading, we might have to invoke one constructor from another
constructor. In such a case, we cannot call the constructor explicitly. Instead, we have to use this
keyword.

Here, we use a different form of this keyword. That is, this(). Let's take an example,

class Complex {

private int a, b;
// constructor with 2 parameters
private Complex( int i, int j ){
this.a = i;
this.b = j;
}

// constructor with single parameter


private Complex(int i){
// invokes the constructor with 2 parameters
this(i, i);
}

// constructor with no parameter


private Complex(){
// invokes the constructor with single parameter
this(0);
}

@Override
public String toString(){
return this.a + " + " + this.b + "i";
}

public static void main( String[] args ) {

// creating object of Complex class


// calls the constructor with 2 parameters
Complex c1 = new Complex(2, 3);

// calls the constructor with a single parameter


Complex c2 = new Complex(3);

// calls the constructor with no parameters


Complex c3 = new Complex();

// print objects
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
}
In the above example, we have used this keyword,

to call the constructor Complex(int i, int j) from the constructor Complex(int i)

to call the constructor Complex(int i) from the constructor Complex()

Notice the line,


System.out.println(c1);

Here, when we print the object c1, the object is converted into a string. In this process, the toString() is
called. Since we override the toString() method inside our class, we get the output according to that
method.

One of the huge advantages of this() is to reduce the amount of duplicate code. However, we should be
always careful while using this().

This is because calling constructor from another constructor adds overhead and it is a slow process.
Another huge advantage of using this() is to reduce the amount of duplicate code.

You might also like