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
How many bytes are there?
how to prepare for IT Officers Interview in Banks
What is arrays aslist in java?
What is the difference between access specifiers and access modifiers in java?
How do you square a number in java?
Using callable statement how can you pass out parameters, explain with example?
What are the basic interfaces of java collections framework?
What are the six ways to use this keyword?
Can a class be private?
What is an off by one error in java?
Does hashset allow duplicates in java?
What is pangram in java?
What do you mean by synchronized non access modifier?
Can substring create new object?
What is an example of a keyword?