Determine who can use the definitions that follow.
When comes to determine whether elements accessible, see whether the current scope meets the access requirement.
| position | ease | box | interval | due |
|---|---|---|---|---|
| front | 2.50 | 3 | 6.00 | 2021-01-28T20:29:09Z |
Also called package-private access.
Don’t need to import package-private classes in the same package.
Package-private members (fields and methods) in any cases, inherited or inside public classes, remains package-private.
If Java Class is package-private, it’s invisible outside of the package.
Files in the same directory are implicitly part of the “default package” for that directory.
The element is available to everyone
No one can access that element except the creator.
Anyone trying to access this kind of elements illegally gets compile time error.
| position | ease | box | interval | due |
|---|---|---|---|---|
| front | 2.50 | 3 | 6.00 | 2021-01-28T20:26:42Z |
package package1;
public class Class1 {
public void tryMePublic() {
}
protected void tryMeProtected() {
}
public static void main(String[] args) {
Class1 c = new Class1();
c.tryMeProtected(); // no error
}
}
package package2;
import package1.Class1;
public class Class2 extends Class1 {
doNow() {
Class1 c = new Class1();
c.tryMeProtected(); // ERROR: tryMeProtected() has protected access in Class1
tryMeProtected(); // No error
}
}
| position | ease | box | interval | due |
|---|---|---|---|---|
| front | 2.50 | 1 | 0.01 | 2021-01-18T17:00:43Z |
package pkg1;
public class A {
public void publicPrint() {System.out.println("Public print from A");}
}
class AA extends A {
@Override
public void publicPrint() { System.out.println("Public print from AA"); }
}
public class B {
public A makeAA() {return new AA();}
// need upcasting here
// otherwise if return AA, it cannot use outside of the package
// e.g., in class C:
// new B().makeAA().publicPrint() will cause error
}
package pkg2;
public class C {
public static void main(String[] args){
B b = new B();
A aa = b.makeAA();
aa.publicPrint();
}
}
/* Output
Public print from AA
*/
package pkg1;
class Base {
void packagePrint() { System.out.println("Package print from Base"); }
public void publicPrint() { System.out.println("Public print from Base"); }
}
public class A extends Base{ }
package pkg2;
import pkg1.A;
public class C extends A {
public static void main(String[] args){
C c = new C();
c.publicPrint();
}
}
/* Output
Public print from Base
*/