Java : Access Modifiers – A tricky point to remember

With a mission to complete Java basic developer certification on July 5th,  I have been still not so regular with my training.  At Chapter 29 out of 72 at the Udemy course.  Chapter 29 is about Access Modifiers, and there is one thing to remember about “Protected” declaration for variables and methods.

As the usual explanation goes –

> Private –  Accessible only from within the Class

> Public – Accessible from anywhere in the world

> No Access Modifier –  Accessible within the same package

> Protected – Accessible within the same package and subclasses in other packages

The tricky part is : Subclasses in other packages.

Here is the code I wrote to refresh this concept –

// General.java in Package “Fruit” –

package Fruit;

public class General {

private String generalname;
public String name;

protected int quantity;
int sold;

public General(String name) {

generalname = “Fruit”;
this.name = name;
System.out.println(“General constructor with name called”);
}

public General(int quantity, int sold)
{
this.quantity = quantity;
this.sold = sold;
System.out.println(“General constructor with quantity called”);
}

}

// Apple.java in default package

import Fruit.General;

public class Apple extends General{

int value;

public Apple(int quantity, int sold)
{
super(quantity, sold);
value = 10;

}
public void displayInfo()
{
System.out.println(“Quantity = ” + quantity);
// within the same package, cannot access sold variable
//System.out.println(“Sold = ” + sold);
System.out.println(“Value = ” + value);
}

}

// App.java in default package which contains the main method

import Fruit.General;

public class App {

public static void main(String[] args) {

General g = new General(“Saanvi”);
General g1 = new General(10,5);

Apple a = new Apple(50,5);
a.displayInfo();   // This works – as the protected members can be accessed within the subclass in a different package

system.out.println(a.quantity); // This will not work, as the variable quantity is not PUBLIC to be accessed from main method
}

}

Also, another thing to note is that the variable “sold” has no access modifier and hence has package level visibility. It is not visible within the class Apple.

A rather neat explanation is provided in this stackexchange Q & A thread. Take a look when time permits.

Happy Coding! 😀

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s