Как добавить Interface в пакет?
Установил новую версию IntelliJ Idea (Community Edition 2017.3.4×64). В предыдущей версии IntelliJ все было просто и понятно: New ⇒ Class ⇒ имя класса ⇒ Interface . А теперь что-то поменялось. Открывается New ⇒ File ⇒ Enter a file name ⇒ Ввожу имя файла – нет возможности выбрать опцию Interface. Столкнулся с неожиданной проблемой и не знаю что делать. Существует ли возможность еще как-то добавлять Interface в пакет, а не только на пакете Правая клавиша ⇒ New ?
Отслеживать
user328896
задан 30 янв 2018 в 21:42
1 3 3 бронзовых знака
2 ответа 2
Сортировка: Сброс на вариант по умолчанию
New ⇒ Java Class ⇒ Вводим имя и выбираем тип класса. Выглядит это примерно так:

Версия: 2020.1.1
#19 – Интерфейсы в Джава

Интерфейсы очень схожи с абстрактными классами. Между ними есть всего несколько отличий. За урок мы научимся использовать интерфейсы на практике в Джава, а также узнаем где и зачем их можно использовать.
Видеоурок
Во многих языках программирования реализована возможность множественного наследования, когда один класс имеет несколько классов родителей. В языке Java такой функциональности нет и чтобы решить эту проблему можно использовать интерфейсы.
Что такое интерфейс?
Интерфейсы очень схожи с абстрактными классами и предоставляют лишь методы без реализации.
В интерфейсах можно записать методы, что должны реализовываться во всех классах, использующих интерфейс. Это удобно, ведь за счёт такого функционала мы можем быть уверены в классах и будем знать что они реализовывают все те функции, что мы предусмотрели заранее.
Как создать интерфейс?
Для создания интерфейса используется ключевое слово Interface :
public interface SomeOne
В интерфейсе можно не прописывать модификаторы доступа и по-умолчанию будет проставлен модификатор public.
Для реализации функционала в интерфейсе необходимо создать класс и указать что он является классом, реализующим определенный интерфейс. Для этого после названия класса пропишите слово implements :
class Person implements SomeOne < // Указали реализацию String name; float happiness; int age; Person(String name, float happiness, int age) < this.name = name; this.happiness = happiness; this.age = age; >// Обязательно должны реализовать все методы из интерфейса // Для реализации прописываем слово @Override @Override public void Change (String val) < // Функционал может быть любым, но должен соответсовать описанному методу // К примеру, данная функция ничего не должна возвращать, так как тип данных у неё void this.name = val; System.out.print("Теперь человека зовут - " + val); >>
Для реализации нескольких интерфейсов их можно прописать через запятую в классе после слова implements .
Extract interface
With the Extract Interface refactoring you have the following options:
- Create an interface based on the methods of a class.
- Rename the original class, and it implements the newly created interface. In such case, IntelliJ IDEA changes all usages of the original class to use the interface where possible.
In addition, static final fields, declared in the initial class, can be moved to an interface. As a result, an interface will be created containing the specific methods and fields. Thereby, the specified class methods become implementations of the corresponding interface methods.
Examples
Here we have a class, and perform Extract Interface refactoring to create an interface based on the methods of the class.
// File AClass.java class AClass < public static final double CONSTANT = 3.14; public void publicMethod() < >public void secretMethod() < >>
// File AClass.java class AClass implements AnInterface < public void publicMethod() < >public void secretMethod() < >// File AnInterface.java public interface AnInterface < double CONSTANT = 3.14; void publicMethod(); >>
Another example of the Extract Interface refactoring, when the Rename original class and use interface where possible option is selected.
public class FormerAClass implements AClass < public void publicMethod() < >public void secretMethod() < >>
public interface AClass < double CONSTANT=3.14; void publicMethod(); >
You can extract an interface from the class that already implements another interface. Let’s extract interface from the class that implements AnInterface . Depending on whether we want AnotherInterface (extracted interface) to extend the AnInterface (existing one) or we want source AClass to implement them both, we will get the following code:
Extracted Interface extends the existing one:
class AClass implements AnotherInterface < public void publicMethod() < //some code here >public void secretMethod() < //some code here >>
public interface AnotherInterface extends AnInterface < >
Source class implements both interfaces.
class AClass implements AnInterface, AnotherInterface < public void publicMethod() < //some code here >public void secretMethod() < //some code here >>
public interface AnotherInterface < >
Extract an interface
- Select a class in the Project view, Structure view, or place the caret anywhere within a class in the editor.
- From the main menu or from the context menu of the selection, select Refactor | Extract | Interface . The Extract Interface dialog appears.
- To extract a new interface, select the Extract Interface option and specify the name for the new interface. To rename the original class and make it an implementation of the newly created interface, select the Rename original class and use interface where possible option and specify the new name for the original class. IntelliJ IDEA will alter all original class usages to the usages of the implementing only where it is still necessary.
- Specify the package, where the new interface will be located.
- Select the class members you want to be listed in the interface in the Members to form interface area. The list shows all the methods of the class, as well as final static fields (constants).
- In the JavaDoc area, select the action to be applied on the JavaDoc .
- To leave it where it is, select the As is option.
- To copy it to the extracted interface, select the Copy option.
- To move it to the extracted interface, select the Move option.
- Click Refactor to proceed.
- Click Refactor when ready. If IntelliJ IDEA shows you a Refactoring Preview in the Find tool window, review the suggested changes. To have the interface extracted and the proposed changes applied, click Do Refactor .
Создание GUI на IntelliJ Idea

Здорово, други. Срочный вопрос по разработке GUI на IntelliJ Idea. Ребят, с чего начать изучение, что надо скачать для Idea, где в доступной форме можно почитать про это? Спасибо за ответы заранее. Очень расчитываю на вашу помощь.
Комментарии (8)
ЧТОБЫ ПОСМОТРЕТЬ ВСЕ КОММЕНТАРИИ ИЛИ ОСТАВИТЬ КОММЕНТАРИЙ,
ПЕРЕЙДИТЕ В ПОЛНУЮ ВЕРСИЮ
dimaMJ Уровень 25
9 февраля 2015
в этой книге в двух разделах описана работа с интерфейсом, все легко и доступно, может пригодиться )
Izhak Уровень 22
9 февраля 2015
javafx, хотя придётся конечно покопаться, да и на машинах пользователей придётся ставить саму джава машину, а также javafx. Да, и чтобы собрать проект должно быть одно из условий- или у вас в учётной записи на компьютере не должно быть пробелов, или вы должны будете скопировать каталог и поменять в конфиге пару букв-я сейчас не помню, где- когда у вас всё будет работать из идеи, то при окончательной сборке будет ругаться.
Хотя вот с JDK8 она идёт в комплекте
docs.oracle.com/javase/8/javafx/get-started-tutorial/jfx-overview.htm
оттуда отсылки к docs.oracle.com/javase/8/javafx/get-started-tutorial/get_start_apps.htm#BACECIIB
и ещё — визуальную среду для javafx большого смысла ставить на мой взгляд, нет — только портит форму.
Ещё я раньше натыкался на сразу кучу примеров в одном окне, которые можно себе скачать, но сейчас не нахожу так быстро. docs.oracle.com/javase/8/javase-clienttechnologies.htm