Open In App

Java Program to Create a Package to Access the Member of External Class and Same Package

Improve
Improve
Like Article
Like
Save
Share
Report

As the name suggests a package in java that contains all the same kinds of classes, Abstract classes, interfaces, etc that have the same functionality. A Single package can contain many classes, Abstract classes e.g. java.util package etc.

There are two types of packages:

  1. Built-in-package: These are the packages that are predefined in the java jar file. The most commonly used package in java. util and java.io package in java.
  2. User-defined package: These packages are created by the user that used to store related classes some other utility functions, interfaces and abstract classes, etc which are defined for the specific task is called a user-defined package.

Project structure:

Project -- GFG  
           | 
           |  
Package 1 GFG1
           |
          GFG1.java (class)
          
Package 2 GFG2
           |
          GFG2.java (class)
           |
          GFG3.java (class)

Package 1:

GFG1.java

Java




package GFG1;
// Creating Interface
interface GFG1Interface {
    String name = "This is the Interface of GF1";
    void GFG1Interface();
}
public class GFG1 {
   
    // Instance variable
    String name;
   
    // Getter Function
    public String getName() { return name; }
   
    // Setter Function
    public void setName(String name) { this.name = name; }
}


 
Package 2:

GFG3.java

Java




package GFG2;
// Creating Interface
interface GFG3Interface {
    String name = "GFG";
    public void interfaceGFG();
}
// Creating Abstract class
abstract class GFGabstract {
    String name = "GFGAbstract";
   
    // Abstract Method
    abstract public void print();
}
public class GFG3 {
   
    // Instance Variables
    int first;
    int second;
   
    // Creating Constructor
    GFG3(int a, int b)
    {
        this.first = a;
        this.second = b;
    }
   
    // Creating add Function
    public int add() { return this.first + this.second; }
}


 
Accessing the members of package 1 class in package 2 class:

GFG2.java

Java




package GFG2;
// Importing the members of GFG1 package
import GFG1.*;
public class GFG2 implements GFG3Interface {
 
    @Override public void interfaceGFG()
    {
        System.out.println(
            "This is the interface of the GFG3class");
    }
    public static void main(String args[])
    {
        // Creating object of class GFG1
        GFG1 ob = new GFG1();
       
        // Calling setName Function
        ob.setName("GFGsetter");
        System.out.println(ob.getName());
       
        // Creating object of class GFG2
        GFG2 ob2 = new GFG2();
 
        ob2.interfaceGFG();
    }
}


 
Output:

 



Last Updated : 18 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads