- Java — разница между extends и implements на примерах
- Ключевое слово extends в Java
- Ключевое слово implements в Java
- Заключение
- Java implements Keyword
- Definition and Usage
- Notes on Interfaces:
- Why And When To Use Interfaces?
- Multiple Interfaces
- Example
- Related Pages
- implements in Java
- What is “implements” in Java?
- Example 1: Implementing a Default Method From an Interface in Java
- Example 2: Implementing Abstract Methods From an Interface in Java
- Example 3: Implementing Multiple Interfaces in Java
- Conclusion
- About the author
- Umar Hassan
Java — разница между extends и implements на примерах
После продолжительного программирования на C++ переходить на Java бывает болезненно. С одной стороны прославленный сборщик мусора, а с другой огромное множество принципиальных различий в подходах к программированию. Об одном таком отличии я сегодня расскажу подробнее.
Речь пойдет о наследовании в Java. В отличии от C++, где наследование могло быть множественным, здесь это не совсем так. Кроме того, привычный синтаксис через «:» заменился на целых два ключевых слова: extends и implements. Начну с первого.
Ключевое слово extends в Java
Действие ключевого слова в точности совпадает с его переводом, один класс расширяет другой, что является классическим наследованием. Правила видимости полей и методов сохранились: private доступны только в самом классе, protected в самом классе и во всех наследниках, к public методам и полям можно обращаться откуда угодно. Главное отличие от «сишного» наследования в том, что можно расширять только один класс. Я сейчас не буду рассуждать о том, насколько это удобно, скажу только, что со множественным наследованием в C++ постоянно творилась какая-то каша.
Небольшой пример наследования с помощью ключевого слова extends. Напишем класс Door, который будет описывать характеристики двери, мы можем создать объект этого класса и работать с ним, как с «просто дверью». С другой стороны напишем еще два класса: IronDoor и WoodDoor, которые будут расширять класс Door(== наследуются от класса Door), т.е. добавят свои характеристики к базовым.
//Базовый класс "дверь" public class Door < //Допустим, что у любой двери есть цена protected int price; //Этот метод тоже наследуется protected void doSomething() < System.out.println("Door is doing something"); >//Этот метод доступен исключительно в классе Door private void onlyForDoor() < >> //Железная дверь public class IronDoor extends Door < //Уровень защиты определен только для железных дверей private int protectionLvl; IronDoor(int price, int protectionLvl) < this.price = price; this.protectionLvl = protectionLvl; >> //Деревянная дверь public class WoodDoor extends Door < //Характеристика "порода древесины" доступна только деревянной двери private String woodType; WoodDoor(int price, String woodType) < this.price = price; this.woodType = woodType; >>
Ключевое слово implements в Java
С ключевым словом implements связано чуть больше хитростей. Слово «имплементировать» можно понимать, как «реализовывать», а в тот самый момент, когда возникает слово «реализовывать», где-то недалеко появляются интерфейсы. Так вот конструкция public class Door implements Openable означает, что класс дверь реализует интерфейс «открывающийся». Следовательно класс должен переопределить все методы интерфейса. Главная фишка в том, что можно реализовывать сколь угодно много интерфейсов.
Зачем это нужно? Самый простой пример, который приходит в голову, два интерфейса: Openable и Closeble. В первом метод open, и метод close во втором. Они помогут научить нашу дверь закрываться и открываться.
public interface Openable < void open(); >public interface Closeble < void close(); >public class Door implements Openable, Closeble < protected int price; protected void doSomething() < System.out.println("Door is doing something"); >//Реализованные методы @Override public void open() < >@Override public void close() < >>
В классах-потомках двери(железная и деревянная двери) тоже появятся методы открыть/закрыть, реализованные в классе Door. Но никто нам не запрещает их переопределить.
public class IronDoor extends Door < private int protectionLvl; IronDoor(int price, int protectionLvl) < this.price = price; this.protectionLvl = protectionLvl; >//Переопределяем методы @Override public void open() < System.out.println("The IRON door is opened"); >@Override public void close() < System.out.println("The IRON door is closed"); >>
Заключение
Итак, главное отличие в том, что extends используется для наследования от класса в прямом смысле этого слова, а implements позволяет «реализовать интерфейс». На первый взгляд это кажется лишним, неудобным и непонятным, но стоит пару раз использовать по назначению и все встает на свои места. На сегодня у меня все, спасибо за внимание!
Java implements Keyword
An interface is an abstract «class» that is used to group related methods with «empty» bodies:
To access the interface methods, the interface must be «implemented» (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the «implement» class:
// interface interface Animal < public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) >// Pig "implements" the Animal interface class Pig implements Animal < public void animalSound() < // The body of animalSound() is provided here System.out.println("The pig says: wee wee"); >public void sleep() < // The body of sleep() is provided here System.out.println("Zzz"); >> class MyMainClass < public static void main(String[] args) < Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); >>
Definition and Usage
The implements keyword is used to implement an interface .
The interface keyword is used to declare a special type of class that only contains abstract methods.
To access the interface methods, the interface must be «implemented» (kinda like inherited) by another class with the implements keyword (instead of extends ). The body of the interface method is provided by the «implement» class.
Notes on Interfaces:
- It cannot be used to create objects (in the example above, it is not possible to create an «Animal» object in the MyMainClass)
- Interface methods does not have a body — the body is provided by the «implement» class
- On implementation of an interface, you must override all of its methods
- Interface methods are by default abstract and public
- Interface attributes are by default public , static and final
- An interface cannot contain a constructor (as it cannot be used to create objects)
Why And When To Use Interfaces?
To achieve security — hide certain details and only show the important details of an object (interface).
Java does not support «multiple inheritance» (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below).
Multiple Interfaces
To implement multiple interfaces, separate them with a comma:
Example
interface FirstInterface < public void myMethod(); // interface method >interface SecondInterface < public void myOtherMethod(); // interface method >// DemoClass "implements" FirstInterface and SecondInterface class DemoClass implements FirstInterface, SecondInterface < public void myMethod() < System.out.println("Some text.."); >public void myOtherMethod() < System.out.println("Some other text. "); >> class MyMainClass < public static void main(String[] args) < DemoClass myObj = new DemoClass(); myObj.myMethod(); myObj.myOtherMethod(); >>
Related Pages
Read more about interfaces in our Java Interface Tutorial.
implements in Java
In Java, there can be situations where the developer needs to place the associated functionalities at different locations or files to sort out the code complexity. For instance, sorting the functionalities separately considering their association, and integrating them in accordance with the requirement. In such cases, the “implements” keyword in Java is of great aid in implementing the defined interface(s) from time to time.
This write-up will demonstrate the usage of the “implements” keyword in Java.
What is “implements” in Java?
The term “implements” corresponds to a keyword utilized to integrate the related methods by implementing the interface. These methods can be “abstract” or “default” and the interface can be implemented in the same or different file.
public interface InterfaceName {
void temp1 ( ) ;
default void temp2 ( ) {
//body
}
}
class abc implements InterfaceName {
//class body
}
- “temp1” is an abstract method.
- “temp2” is the default method.
- “class abc” refers to the class that implements the “InterfaceName” interface via the “implements” keyword.
Example 1: Implementing a Default Method From an Interface in Java
In this example, an interface can be implemented from an external file using the “implements” keyword, and the default method of the interface can be imported and executed from this file via the class object.
Interface Code
Go through the following code snippet:
public interface age {
void id ( ) ;
default void city ( ) {
System . out . println ( «The city is: London» ) ;
} }
In the interface file, apply the following steps:
- First, create an interface named “age”.
- Within this interface, first, specify the abstract method, i.e., “id()”.
- Note: The abstract method does not have a body.
- Now, define the default method named “city()” displaying the stated message.
Now, follow the below-provided code:
class Student implements age {
public void id ( ) {
System . out . println ( «The id is: 1» ) ;
} }
public class interfacedefault {
public static void main ( String args [ ] ) {
Student object = new Student ( ) ;
object. id ( ) ;
object. city ( ) ;
} }
According to the above class code, apply the below-provided steps:
- Define the class “Student” implementing the discussed interface, i.e., “age” using the “implements” keyword.
- In the class, define the method “id()” specified in the interface.
- In the “main()” method, create an object of the class named “object” using the “new” keyword and the “Student()” constructor, respectively.
- After that, invoke the abstract and default interface methods by referring to the created class object, respectively.
In this output, it can be observed that the defined default method from the interface is implemented appropriately.
Example 2: Implementing Abstract Methods From an Interface in Java
In this particular example, the abstract methods, i.e., “comprising no body” in the interface can be implemented in the class.
Interface Code
Consider the below-given interface code:
In this code, simply include the provided methods, i.e., “abstract” comprising no “body”.
Let’s overview the below-provided lines of class code:
class sample implements age {
public void id ( ) {
System . out . println ( «The id is: 1» ) ;
}
public void city ( ) {
System . out . println ( «The city is: London» ) ;
} }
public class interface2 {
public static void main ( String args [ ] ) {
sample object = new sample ( ) ;
object. id ( ) ;
object. city ( ) ;
} }
According to this code block, apply the following steps:
- First of all, declare the class “sample” implementing the allocated interface with the help of the “implements” keyword.
- Define the methods “id()” and “city()” having the stated messages, respectively.
- In the “main()” method, create a class object with the help of the “new” keyword and the “sample()” constructor, respectively.
- Lastly, invoke the defined methods via the created object.
Example 3: Implementing Multiple Interfaces in Java
This example implements multiple interfaces via “class” by associating the methods with each of the interfaces, separately in the same file:
interface First {
public void id ( ) ;
}
interface Second {
public void city ( ) ;
}
class Student implements First, Second {
public void id ( ) {
System . out . println ( «The id is: 1» ) ;
}
public void city ( ) {
System . out . println ( «The city is: London» ) ;
} }
public class interfacedefault {
public static void main ( String args [ ] ) {
Student object = new Student ( ) ;
object. id ( ) ;
object. city ( ) ;
} }
According to the above code snippet:
- Define two interfaces named “First” and “Second” accumulating the stated abstract methods, respectively.
- Now, declare a class named “Student” and implement the defined interfaces via the “implements” keyword.
- In the class definition, define the specified abstract methods previously(in the interface).
- Finally, in the “main()” method, create a class object via the discussed approach and invoke the defined methods.
The above outcome indicates that the abstract methods in the interfaces are implemented successfully.
Conclusion
The term “implements” in Java corresponds to a keyword utilized to integrate the methods by implementing the interface. These methods can be “abstract” or “default”. The former method is just specified in the interface while the latter method is defined and invoked from the interface. This article guided to apply the “implements” keyword in Java.
About the author
Umar Hassan
I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.