118.
119.
as sub–classes that are outside the package too. When a
member has the default access specifier,
that member is
accessible only to classes within the package, it is not
accessible outside the package.
Is the following code snippet valid? Explain.
package demo1;
public class MyClass1 {
int a; //Line 1
}
package demo2;
public class MyClass2 {
public void doSomething() {
MyClass1 obj = new MyClass1(); //Line 2
obj.a = 5; //Line 3
}
}
Answer:
The above code is not valid and will
cause a compilation error at
line 3. The class MyClass1 is in a package called demo1. It has
a field a. Since no access specifier is included explicitly,
this field
has default access. The class MyClass2 is in a package called
demo2. The doSomething() method access the field a from
MyClass1 at Line 3. A field with default
access is not accessible
outside the package so Line 3 will cause a compilation error.
Do'stlaringiz bilan baham: