top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain Default Access modifier in Java ?

+1 vote
310 views
Explain Default Access modifier in Java ?
posted Dec 29, 2014 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

If a particular class or class member does not have any access modifier specified then it's access modifier is default.
Now if a class has no (default) access modifier then it is visible in only the package in which it is defined.
If an instance variable( i.e data member) in a class has no (default) access modifier then it visible within all other classes within same package and also visible within all subclasses of this class. (Within the package or outside package.)
Ex:

Package pkg1:----------- 
class DefaultClass{
}

class Test{
    DefaultClass obj=new DefaultClass(); //Valid
}

Package pkg2:-----
import pkg1.*
class Test{
    DefaultClass obj=new DefaultClass(); //INVALID
}


AGAIN:
Package pkg1:-----------
public class DefaultClass{
   int x=10;
}

class Test{
    DefaultClass obj=new DefaultClass(); 
    System.out.println(obj.x);
}

Package pkg2:-----
import pkg1.*
class Test{
    DefaultClass obj=new DefaultClass(); 
    System.out.println(obj.x); // INVALID
}

class Subclass extends pkg1{
    x=20;   //accessing parent class member is VALID
}
answer Dec 29, 2014 by Prakash
...