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
Can inner class be public in java?
Why do we override tostring method in java?
What is data string?
Which sorting algorithm is in place?
What are the two ways to create a thread?
Is Java a dying language?
What is boolean data type in java?
What is the concept of multithreading?
What happens if we don’t define serial version uid?
How do you do absolute value in java?
Give an example of call be reference significance.
How to restrict a member of a class from inheriting by its sub classes?
how to deploy tomcatserver to weblogic server? write d following steps?
Can you call a method in a method?
What do negative exponents mean?