what is the difference between the "protected and default"
modifiers?
Answer Posted / waheeb
we cannot make a class protected. however it is observed
that both default and protected modifiers exhibit same
characteristics. both are not accessible outside the
package and are accessible within the same package whether
the class is inheriting from the superclass or not.
for example:
package pack1;
public class SuperClass {
public int publicvar;
protected int protectedvar;
private int privatevar;
int defaultvar;
public void publicmethod() {
System.out.println("Public Method");
}
protected void protectedmethod() {
System.out.println("Inside Protected
Method");
}
private void privatemethod() {
System.out.println("Inside Private Method");
}
void defaultmethod(){
System.out.println("Inside Default Var");
}
}
class subclass extends SuperClass{
public static void main(String args[]){
SuperClass obj = new SuperClass();
obj.protectedvar = 10;
obj.defaultvar = 10;
obj.defaultmethod();
/*
protected and default feilds accessible in
the same
*/
}
}
class anotherClass{
public static void main(String args[]){
SuperClass obj = new SuperClass();
obj.protectedvar = 10;
obj.defaultvar = 10;
/* protected and default feilds accessible
in the same
package without extending*/
}
}
| Is This Answer Correct ? | 0 Yes | 3 No |
Post New Answer View All Answers
What is the use of generics? When was it added to the Java development Kit?
Explain about anonymous inner classes ?
What are classloaders?
What is data member in java?
Give a practical example of singleton class usage?
what is the difference between process and thread? : Java thread
What is the use of list in java?
What is the difference between Error, defect,fault, failure and mistake?
Explain different types of thread priorities ?
Does java set allow duplicates?
What is the benefit of inner / nested classes ?
How do you check if two given string are anagrams?
Is java jre still free?
How do you do a line break in java?
What is a function in programming?