Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected Vs default access modifiers?

 
Mallik Avula
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends
what is the exact difference between protected and default access modifiers?
as i know that "protected" can be accessible only from subclasses regardless of whether that class is in same package or not
and "default" can be accessible from any class in the same package regardless of whether that is extended or not.

but my code:

class Base{

protected void method2(){
System.out.println("base thothd2");
}
}

public class Test {


public static void main(String[] args){

Base t = new Base();
t.method2();
System.out.println("asdf");

}

}

output is:
Base method2
asdf

so, that means a class can access protected members without extending if that class in same package.
is it write?(still i cann't believe)
give me clarification whether it is write or any other involved.....

regards
Mallik
 
Mallik Avula
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi friends
i am very sorry for small mistake
is it right? not(is it write)
i am really very sorry

regards
Mallik
 
Srinivasan thoyyeti
Ranch Hand
Posts: 557
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Access Specifier scope
--------------------------------------------
"public" scope protected access + any other outer pack classes
"protected" scope default pack access + any sub class relation
"default" scope (means absence of access specifier)-- classes in same pack
"private" - methods in same class in which its defined.
 
Gaurav Pavan Kumar Jain
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mallik

protected provides you access in following conditions:-

1) From Same class
2) From any class from same package
3) from a subclass from same package
4) From a Subclass outside the package

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic