Packages & Access Modifiers

invisibleufo101·2024년 9월 14일

Java

목록 보기
8/10
post-thumbnail

Packages

  • Definition: Packages function like directories. They help organize classes and avoid naming conflicts.
  • Class Uniqueness: Classes with the same name are considered different if they belong to different packages.

Example Structure:

com
  └── myCompany
      └── A class

com
  └── otherCompany
      └── A class

Even though both classes are named "A", since they are in different packages, the compiler recognizes them as individual classes.

Package Naming Rules

  • Cannot Start: With numbers
  • Allowed Characters: Letters, digits, _, and $
  • Lowercase: Must be all lowercase
  • Reserved Keywords: Cannot use reserved names like java

Importing Classes

Allows the use of classes from different packages.
We can either specify the class that we want to import or use wildcard(*) selection to import ALL classes in the given package.

    import com.company.ClassName; // <- specific
    import com.company.*;  // <- wildcard import

Access Modifiers

  • public: Accessible from any other class.
  • private: Accessible only within the same class.
  • protected: Accessible within the same package and subclasses.
  • default (no modifier): Accessible only within the same package.

Example:

In package01:

package package01;

class A {
}

public class B {
    A a;  // Accessible because A is in the same package

    public static void foo() {
        System.out.println("foo");
    }
}

In package02:

package package02;

public class C {
    public static void main(String[] args) {
        B b = new B();
        b.foo();  // Accessible because foo() is public
    }
}

But if foo() was private:

In package01:

package package01;

public class B {
    A a;  // Accessible because A is in the same package

    private static void foo() {
        System.out.println("foo");
    }
}

In package02:

package package02;

public class C {
    public static void main(String[] args) {
        B b = new B();
        b.foo();  // Not accessible because foo() is private
    }
}

Allowed Access Modifiers in each scope

  • Class: public, default
  • Constructor: public, default, private, protected
  • Method: public, default, private, protected
  • Field: public, default, private, protected

Level of Encapsulation (From most accessible to most closed):

public > protected > default > private

profile
하나씩 차근차근

0개의 댓글