Java import project class

How do I use classes from another project in IntelliJ IDEA?

I have two IntelliJ IDEA Java projects; ProjectA and ProjectB. I want to import and use code from ProjectA in ProjectB. How do I do this? In Eclipse I would simply go to ProjectB’s Build Path settings and add ProjectA.

4 Answers 4

You can create dependency between these projects (Make project B dependent on project A) What it does is essentially compiles project A first then put its compiled jar as dependency to Project B for compiling or running. You can do this manually also.

Steps in IDEA ( You won’t need these below steps if you follow below mentioned best practices):

  1. Right click on project and select open module settings
  2. Go to dependencies tab
  3. click plus sign and add the module you want to use.
  1. Never use project class in another project, always create a nice interface and use that interface in other projects.
  2. If possible use Dependency Injection to manage different projects and their dependencies (this internally uses interfaces to do this)
  3. Use build tool like ant/maven/ivy etc to manage build process.
  4. Enjoy 🙂

I have tried following these steps, but IDEA can’t seem to find the classes (via autocomplete at least) that I need from the external module.

Eclipse’s concepts of «workspace» and «project» are matched by IntelliJ IDEA’s «project» and «module». So one way of doing this is to create a project, say ProjectAB, and import your two existing ProjectA and ProjectB as modules, I’ll call them ModuleA and ModuleB.

Right after that make sure that in the project tree both modules have correct folders marked as «source» folders (in my case they are ModuleA/src/main/java and ModuleB/src/main/java).

Then you have to configure ModuleB to depend on ModuleA (ModuleB > Dependencies> Add > Module Dependency).

Источник

Import a custom class in Java

What is the actual problem you are having, since you don’t have to import classes that are in the same package?

8 Answers 8

If all of your classes are in the same package, you shouldn’t need to import them.

Simply instantiate the object like so:

CustomObject myObject = new CustomObject(); 

Import by using the import keyword:

But since it’s the default package and same, you just create a new instance like:

elf ob = new elf(); //Instance of elf class 

It wouldn’t matter if it wasn’t the default package — you don’t have to import classes that are in the same package.

In the same package you don’t need to import the class.

Otherwise, it is very easy. In Eclipse or NetBeans just write the class you want to use and press on Ctrl + Space . The IDE will automatically import the class.

Читайте также:  Прозрачность в слое

You can import a class with import keyword after package information:

package your_package; import anotherpackage.anotherclass; public class Your_Class

You can instance the class with:

Anotherclass foo = new Anotherclass(); 

I see the picture, and all your classes are in the same package. So you don’t have to import, you can create a new instance without the import sentence.

First off, avoid using the default package.

Second of all, you don’t need to import the class; it’s in the same package.

If your classes are in the same package, you won’t need to import. To call a method from class B in class A, you should use classB.methodName(arg)

According Oracle and Sun doc, a class can use all classes from its own package and all public classes from other packages. You can access the public classes in another package in two ways.

  • The first is simply to add the full package name in front of every class name. For example: java.util.Date today = new java.util.Date();
  • The simpler, and more common, approach is to use the import statement. The point of the import statement is to give you a shorthand to refer to the classes in the package. Once you use import, you no longer have to give the classes their full names. You can import a specific class or the whole package. You place import statements at the top of your source files (but below any package statements). For example, you can import all classes in the java.util package with the statement Then you can use without a package prefix. import java.util.*; // Use class in your code with this manner Date today = new Date();

As you mentioned in your question that your classes are under the same package, you should not have any problem, it is better just to use class name.

If you have the java files under the same package, you will not need to import the classes within those java files. Simply instantiate an object and you will have access. For example, if you need to access class named My_Class from another file within the same package:

My_Class object = new My_Class(); 

Now, if you put a . dot after typing object, you will gain access to all the methods and attributes from the class.

Now, if you don’t have the files under the same package, you can import the Class. Just type:

import Package_Name.Class_name 

Where Package_Name represents the name of the package in which the class exists and Class_name being the name of the class you want to import.

Источник

How to import my own class?

and I want to import this class after compile it in another source file called Test.java exists in the same directory , and here what Test.java contains :

import myClass ; public class Test < public static void main (String []args) < myClass Rudaina = new myClass(); Rudaina.setHerAge(30); >> 
Test.java:1: error '.' expected import myClass ; ^ Test.java:1: error '.' expected import myClass ; ^ 

5 Answers 5

Your class myClass is also in package called myClass , which can be a cause of confusion.

Читайте также:  Get product price html woocommerce

This is called the fully qualified name of the class.

A package is meant to group classes which are conceptually related. Having a package named after a single class is not very useful.

You could name your package after the name of your project. For instance, you could name it

And then import your class like this:

import assignment1.myClass; 

thank you very much my friend but I have one more question if I want to import myClass without packaging it what I must do ?

While what everyone wrote is true, since the two files are in the same directory, no import should be necessary.

FYI, it is customary to capitalize the names of classes.

It’s better to put the same package name or a different one as mention below on top of the Test.java file;

package myClass; //or some other name also viable 

Then when you compile you can do like this;

javac -d . myClass.java javac -d . Test.java 

The -d specifies the destination where to put the generated class file. You can use any directory name like /home (in case of Linux), d:/abc (in case of windows), etc. If you want to keep the package within the same directory, you can use the .(dot).

After that use the import statement inside Test.java like this;

After that when you run the Test class do like this;

java myClass.Test //myClass in here is package name if you use some different package name use that 

Источник

Как подключить класс в Java, все тонкости импорта класса

Lorem ipsum dolor

В Джава присутствуют стандарты, которые регламентируют правила написания информации о классе или «пакете класса».

Вот стандартный шаблон оформления описания:

p ackage;

public class

>

При этом необходимо помнить, что в описании наименования «пакета классов» обязано присутствовать сходство с описанием наименования папки классов, где расположена структура пакетов. Допустим , у нас присутствует такая строчка: «. \src\drop\codernet\mytasks.java», тогда она будет записана в таком формате:

package drop.codernet;

public class MyTasks

>

Импорт классов в Java

Напишем

Импорт классов в Java — это действие, при котором программист заимствует классы из разнообразных «классовых пакетов», предварительно указав используемые «пакеты и классы» в собственном рабочем документе.

У классов в Джава присутствует такое понятие , как «полноценное уникальное наименование класса». Оно состоит из двух частей: «наименовании класса» и «наименовании классовых пакетов». Как правило, «полноценное название класса» может быть достаточно удлиненным , к примеру: «java.until.MyArrayList», где:

  • «java.until» — название « классового пакета » ;
  • «MyArrayList» — название самого класса.

Причем это не самое длинное «полноценное название класса». Ведь , когда в документе тысячи классов, а уникальное название обязано быть исключительно в единственном экземпляре, тогда н ес ложно догадаться, какие длинные названия могут присутствовать в разрабатываемом документе. Но печалит не длина названи я используемых классов, а то , что их постоянно нужно использовать в коде — это ужасно неудобно и долго. Чтобы упростить эту задачу , был придуман импорт класса в Java.

Читайте также:  Non break space in html

Импорт класса в Java открывает уникальную возможность применять укороченное название класса вместо удлиненного. Но для этого компилятору необходимо указать, какому «полноценному уникальному названи ю класса» идентично укороченное название, используемое программистом в собственной разработке программного обеспечения.

Рассмотрим небольшой программный скрипт:

package drop.codernet.mytasks.mytask01;

import java.util.ScannerList;

import drop.testing.distruct.specialist.MyArrayList;

public class MySolution

public static void main(Strings[] args)

ScannerList console = new ScannerList(Systems.in);

MyArrayList lists = new MyArrayList();

>

>

Если не применять импорт класса Java в вышеописанном программном скрипте, тогда его код будет примерно такого формата:

package drop.codernet.mytasks.mytask01;

public class MySolution

public static void main(Strings[] args)

java.util.ScannerList console = new java.util.ScannerList(Systems.in);

drop.testing.distruct.specialist.MyArrayList lists = new drop.testing.distruct.specialist.MyArrayList();

>

>

Заключение

Импорт класса в Java является доступным способом программиста применять в собственной разработке классовые инструменты из разнообразных сторонних классовых структур, а также сокращать «полноценные уникальные названия классов» до коротких и удобных названий. По сути, импорт класса в Джава — это способ писать код чище, практичнее и быстрее.

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

import from another java project in eclipse

I’m working on two projects in eclipse and I would like to import some classes from project a to project b. What should I do? Is there a way of doing it without adding the project to the build path ?

can you clarify how to import class from another project ? I’m getting error The import can not be resolved

Found the problem; I didn’t specify any package for class in the project which I had included under Projects. Found this issue through stackoverflow.com/questions/2335211/…

1 Answer 1

add project A to project B’s build path.

Follow these steps:
Edits by @David B
Right click on project B’s folder in eclipse —> properties —> build path —> projects —> add.
Now add project A

thanks! just to be more explicit for future reference of other readers: right click on project b’s folder in eclipse —> properties —> build path —> projects —> add.

Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью