In Java, packages and access modifiers are used to control the visibility and accessibility of classes, methods, and variables within a program. Let’s take a look at each of them:
package
keyword at the top of the Java source file.com.example.myapp
).import
statement or reference it using the fully qualified class name.public
, protected
, private
, and the default (no explicit modifier).public
: The class, method, or variable is accessible from any other class or package.protected
: The class, method, or variable is accessible within the same package and subclasses (even if they are in a different package).private
: The class, method, or variable is only accessible within the same class.Here’s an example demonstrating the usage of packages and access modifiers:
package com.example.myapp; // Importing a class from another package import com.example.otherpackage.OtherClass; // Class with public access modifier public class MyClass { // Variables with different access modifiers public int publicVar; protected int protectedVar; private int privateVar; int defaultVar; // default access modifier // Methods with different access modifiers public void publicMethod() { // Method implementation } protected void protectedMethod() { // Method implementation } private void privateMethod() { // Method implementation } void defaultMethod() { // Method implementation } // Using a class from another package public void useOtherClass() { OtherClass other = new OtherClass(); // Access public members of OtherClass } }
In the above example, the MyClass
is declared with the public
access modifier, allowing it to be accessed from other packages. The variables and methods within the class have different access modifiers demonstrating their visibility and accessibility according to the defined access modifiers. The useOtherClass()
method demonstrates the usage of importing a class from another package.
Remember to properly organize your code into packages and choose appropriate access modifiers based on your design requirements and encapsulation principles.
Copyright ©TechOceanhub All Rights Reserved.