How to Import Custom Class in Java?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc. In this article, we will discuss how to import custom classes from one project to another project or in the same project.
Custom classes are created by the user for a particular purpose. These classes are not present in the system library of the project. Consider the structure of the project depicted below as follows:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
ProjectName:Main1 | | First(package)[ GFG1.java , GFG2.java ] (classes) | Second(package)[GFG3.java] (class)
Note: In order to get through the concept, one must go through access modifiers in java to understand the concept of the scope of classes, members, and methods.
Here we will be going through both the structure types as follows which later on will be implementing the same further below:
- Custom class within the same package
- Custom class from another package
Implementation: Importing classes for the same project
Classes in the same project can be imported into any other class in the same project without any import statement in the particular class of the project. Because, by default, all the class members and methods are of default modifier and, according to the scope of the default modifier, they can be accessed in the same package / same package subclass without importing the class. Refer to the above table.
Example 1: GFG1.java
Example 2: GFG2.java
Let us do dwell on next where we will be importing custom class from another package.
Classes are imported between the different packages only when particular that need to be imported are marked as public and its member and methods should be of public so that they can be used outside its package.
Example 1: Second package class
Above second package class is imported to the class of first package Structure: Second:(Package) | GFG3 First:(Package) | GFG2
Example 2: First package class
Addition 3 Subtract 1