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


Please Help Members By Posting Answers For Below Questions

How many bytes are there?

541


how to prepare for IT Officers Interview in Banks

1505


What is arrays aslist in java?

522


What is the difference between access specifiers and access modifiers in java?

577


How do you square a number in java?

558






Using callable statement how can you pass out parameters, explain with example?

591


What are the basic interfaces of java collections framework?

608


What are the six ways to use this keyword?

610


Can a class be private?

518


What is an off by one error in java?

504


Does hashset allow duplicates in java?

582


What is pangram in java?

515


What do you mean by synchronized non access modifier?

569


Can substring create new object?

561


What is an example of a keyword?

546