The default and protected access modifiers are identical modifiers with only one difference.
public class Outerclass
{
void test() //default access
{
System.out.println(“Outer Class”);
}
}
import book.*;
class Innerclass
{
static public void main(String args[])
{
Outerclass oc= new Outerclass();
oc.test(); // compilation error!
}
}
In the above example, there are two packages, book and book1. The package book has a class Outerclass and a method test, which has a default access level. The package book1 has a class Innerclass in which it declares an object of Outerclass. However, when it uses the test() method of the Outerclass, which has a default access level, it will generate a compile-time error
public class read
{
protected int r1=10;
}
package book1;
import book.read;
class Doread extends read
{
public void test()
{
System.out.println(“The value of r1 is:” +r1);
}
}
In the above example, there are two packages, book and book1. The package book has a class read and a protected variable r1. The package book1 has a class Doread, which extends the class read. The compiler will easily access the variable r1 because it inherits the class read.
Click here to download GSSP-Java test study guide and practice question.
Download questions and guide CX310-019 for exam.
