Java Interfaces and Polymorphism
Category Programming Technology
I. Interfaces
1.1 Overview of Interfaces
An interface is a collection of functionalities and can also be considered a data type, being more abstract than an abstract class.
An interface describes the methods that should be present but does not provide their implementation. The implementation is provided by the classes that implement the interface, acting as subclasses of the interface. This separation of definition and implementation optimizes program design.
1.2 Format & Usage of Interfaces
1.2.1 Format of Interfaces
Unlike class definitions which use the class
keyword, interfaces are defined using the interface
keyword.
The interface is defined in a .java
file, and despite using the interface
keyword, it compiles into a .class
file. This allows us to view interfaces as special classes that only contain method declarations.
public interface InterfaceName {
abstractMethod1;
abstractMethod2;
abstractMethod3;
}
1.2.2 Usage of Interfaces
All methods in an interface are abstract, and it is meaningless to directly instantiate an interface to call its methods, which Java does not allow.
A class implements an interface, similar to inheritance but using the implements
keyword.
When a class implements an interface, it essentially declares: "I should have the functionalities of this interface." The implementing class must override the methods to provide specific functionalities.
Format:
class ClassName implements Interface {
override methods from interface
}
After a class implements an interface, it inherits the abstract methods from the interface and must override them to provide specific logic.
1.2.3 Example Code 1
Example
/*
* Java's inheritance is single inheritance, a subclass can only have one parent class (one son can only have one father)
* Java provides a mechanism to handle the limitation of single inheritance, which is interfaces
*
* Interface: An interface is a class more abstract than an abstract class, where all methods are abstract. The relationship between a class and an interface is implementation, using 'implements'
*
* Format:
* interface InterfaceName {
*
* }
*
*/
public class InterfaceDemo {
public static void main(String[] args) {
BillGates gates = new BillGates();
gates.code();
}
}
class Boss {
public void manage() {
System.out.println("Managing the company");
}
}
class Programmer {
public void code() {
System.out.println("Typing code");
}
}
// Bill Gates
class BillGates extends Programmer {
}
1.3 Characteristics of Members in Interfaces
-
-
-
-
1.3.1 Example Code 2
Example
/*
* Characteristics of members in interfaces:
* Only abstract methods
* Only constants
* Methods default to public & abstract
* Methods can only be public & abstract
* Member variables default to public static final
*
* Suggestion: It is recommended to manually include the default modifiers
*
* Note:
* Interfaces cannot be instantiated
* A class implementing an interface must implement all its methods
*/
public class InterfaceDemo2 {
public static void main(String[] args) {
// Animal a = new Animal();
// Animal.num;
}
}
interface Animal {
public static final int num = 10;
public abstract void eat();
}
class Cat implements Animal {
public void eat() {
}
}
1.4 Relationships Between Interfaces and Classes
A: Class-to-class relationships: Inheritance, single inheritance, multiple levels of inheritance
B: Class-to-interface relationships: Implementation, a class can implement multiple interfaces
C: Interface-to-interface relationships: Inheritance, an interface can inherit multiple interfaces
1.4.1 Example Code 3
Example
/*
*
* Class-to-class: Inheritance, single inheritance, multiple levels of inheritance
* Class-to-interface: Implementation, multiple implementation
* Interface-to-interface: Inheritance, multiple inheritance
*/
public class InterfaceDemo3 {
public static void main(String[] args) {
}
}
interface InterA extends InterB {
public abstract void method();
}
interface InterB {
public abstract void function();
}
interface InterC extends InterA {
}
class Demo implements InterC {
@Override
public void method() {
// TODO Auto-generated method stub
}
@Override
public void function() {
// TODO Auto-generated method stub
}
}
1.5 Interface Philosophy
Having learned the code representation of interfaces, let's explore their philosophical aspects by examining real-life examples.
Example: We all know that computers have many ports, and these ports can accommodate various devices. The reason these devices can be plugged in is that they comply with the port's usage rules; otherwise, they wouldn't fit or function. The presence of these ports allows us to use more devices.
Interfaces facilitate later use and maintenance. One party uses the interface (e.g., a laptop), while another party implements the interface (devices plugged into the ports). For example, a laptop uses this rule (interface), and peripheral devices implement this rule (interface).
The collection system extensively uses interfaces:
Collection interface
List interface
ArrayList implementation class
LinkedList implementation class
Set interface
1.6 Advantages of Interfaces
- The relationship between a class and an interface is implementation, which allows for multiple implementations. A class can implement multiple interfaces, whereas class-to-class relationships are single inheritance in Java, breaking the limitations of inheritance.
- Provides rules (e.g., USB interface)
- Reduces the coupling of the program (modular development is possible; defining rules allows each developer to implement their module, increasing development efficiency)
1.7 Differences Between Interfaces and Abstract Classes
1. Commonalities: Both abstract methods and interfaces cannot be instantiated (cannot create objects)
2. Differences
1: Relationship with classes
(1) A class implements an interface, allowing multiple implementations. A class can implement multiple interfaces. A class-to-abstract class relationship is inheritance in Java, which is single inheritance, multiple levels of inheritance. A class can only inherit one parent class but can have a grandparent class.
(2) Differences in members
a. Member variables
Abstract classes can have member variables and constants
Interfaces can only have constants, default modifier public static final
b. Member methods
Abstract classes can have abstract methods and non-abstract methods
Interfaces can only have abstract methods, default modifier public abstract
c. Constructors
Abstract classes have constructors, provided for subclasses
Interfaces do not have constructors
1.8 Athlete Case
1.8.1 Example Code 4
Example
/*
* Basketball players and coaches
Table tennis players and coaches
Basketball players and coaches need to learn English for international visits
Analyze which are classes, which are abstract classes, and which are interfaces based on your knowledge
*/
public class InterfaceTest {
public static void main(String[] args) {
// Create a basketball player object
BasketBallPlayer bbp = new BasketBallPlayer();
bbp.name = "Nv Zhao Yue Ri";
bbp.age = 35;
bbp.gender = "Male";
bbp.sleep();
bbp.study();
bbp.speak();
System.out.println("-------------");
// Create a table tennis coach object
PingpangCoach ppc = new PingpangCoach();
ppc.name = "Liu Pang Zi";
ppc.age = 40;
ppc.gender = "Male";
ppc.sleep();
ppc.teach();
// ppc.speak();
}
}
class Person {
String name; // Name
int age; // Age
String gender; // Gender
// No-argument constructor
public Person() {}
// Parameterized constructor
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
// Eat
public void eat() {
System.out.println("Eating");
}
// Sleep
public void sleep() {
System.out.println("Sleeping");
}
}
// Learning to speak English
interface SpeakEnglish {
public abstract void speak();
}
// Athlete
abstract class Player extends Person {
// Study
public abstract void study();
}
// Coach
abstract class Coach extends Person {
// Teach
public abstract void teach();
}
// Basketball player
class BasketBallPlayer extends Player implements SpeakEnglish {
@Override
public void study() {
System.out.println("Learning to dunk");
}
@Override
public void speak() {
System.out.println("Speaking English");
}
}
// Table tennis player
class PingpangPlayer extends Player {
@Override
public void study() {
System.out.println("Learning to loop the ball");
}
}
// Basketball coach
class BasketBallCoach extends Coach implements SpeakEnglish {
@Override
public void teach() {
System.out.println("Teaching dunking");
}
@Override
public void speak() {
System.out.println("Speaking English");
}
}
// Table tennis coach
class PingpangCoach extends Coach {
@Override
public void teach() {
System.out.println("Teaching looping the ball");
}
}