Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Java access modifiers

  Asked By: Harry    Date: Apr 15    Category: Java    Views: 746
  

I still confuse with this.

The difference between both keywords is just subclass can't access
and override 'private', so as if class 'DerivedClass' doesn't have
the private method (although implicitly they have). Subclass can
access or override methods with 'protected' keyword. Right??

So if I have a base class to -say- generate a document, and maybe
someday I want to create a derived class, which code is better :

//1st
public class BaseGenerator {
private String generateTopDoc() {//call checkSyntax here}
private String generateBottomDoc() {//call checkSyntax here}
private boolean checkSyntax(String s) {...}
public String generateDocument() {
return generateTopDoc().concat(generateBottomDoc());
}
}

//2nd
public class BaseGenerator {
protected String generateTopDoc() {//call checkSyntax here}
protected String generateBottomDoc() {//call checkSyntax here}
private boolean checkSyntax(String s) {...}
public String generateDocument() {
return generateTopDoc().concat(generateBottomDoc());
}
}

//3rd
public class BaseGenerator {
protected String generateTopDoc() {//call checkSyntax here}
protected String generateBottomDoc() {//call checkSyntax here}
protected boolean checkSyntax(String s) {...}
public String generateDocument() {
return generateTopDoc().concat(generateBottomDoc());
}
}

When should i use 'private', and when should I use 'protected'?

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Lughaidh Fischer     Answered On: Apr 15

i m not too clear wht u r asking in ur example..

but genrally in "private" access  level, the same
object have access to all the methods  & variables
eventhough it's private. but outside the class  the
other class can't access a private  member.

"protected" access level, the child (extending) class
has access to all the protected  members if it's in a
SAME PACKAGE. but if the extending child class is in
different package they can't access parent's protected
member but still they can use their own version of
protected members (child.xxx())

"public" access level will allow full access to the
same class, a class in same package, a class in
different package. (means no restriction)

for more information plz check the following link:-

java.sun.com/.../accesscontrol.html

 
Didn't find what you were looking for? Find more on Java access modifiers Or get search suggestion and latest updates.




Tagged: