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'?