1. Interface

1.1 Overview of Interfaces

An interface is a collection of functions. It can also be regarded as a data type, and it is more abstract than an abstract class.Class 。

An interface only describes the methods it should have, without concrete implementation. The concrete implementation is done by the interface's implementation class (equivalent to a subclass of the interface). This separates the definition of functionality from its implementation, optimizing program design.

1.2 Interface Format & Usage

1.2.1 Format of an Interface

Unlike defining a class,classthe difference is that when defining an interface, you need to use theinterfacekeyword.

The file in which the interface is defined is still a.javafile. Although the declaration uses theinterfacekeyword, after compilation it still produces a.classfile. This allows us to regard an interface as a special class that only contains feature declarations.

Definition format:
public interface 接口名 {
    抽象方法1;
    抽象方法2;
    抽象方法3;
}

1.2.2 Usage of Interfaces

All methods in an interface are abstract methods. Directly using `new` on an interface to call methods is meaningless, and Java does not allow this.

The relationship between a class and an interface is an implementation relationship, i.e., a class implements an interface. The action of implementation is similar to inheritance, but the keyword is different; implementation usesimplements。

After other classes (implementation classes) implement an interface, it is equivalent to declaring:"I should have the functionality of this interface."The implementation class still needs to override the methods to implement the specific functionality.

Format:

class 类 implements 接口 {
    重写接口中方法
}

After a class implements an interface, the class inherits the abstract methods from the interface. At this point, the class needs to override these abstract methods to complete the concrete logic.

1.2.3 Case Code 1

Example

/** Inheritance in Java is single inheritance; a subclass can only have one parent class (a son can only have one biological father). * Java provides us with a mechanism to handle the limitation of single inheritance: interfaces. * * Interface: An interface is a class even more abstract than an abstract class. All methods in an interface are abstract methods. The relationship between an interface and a class is implementation, using implements. * interface * * 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("Manage the company"); } } class Programmer { public void code() { System.out.println("Writing code"); } } //Bill Gates class BillGates extends Programmer { }

1.3 Characteristics of Members in an Interface

  • 1. Variables can be defined in an interface, but they must be modified with fixed modifiers: `public static final`. Therefore, variables in an interface are also called constants, and their values cannot be changed. We will explain the `final` keyword later.

  • 2. Methods can be defined in an interface, and methods also have fixed modifiers: `public abstract`.

  • 3. An interface cannot create objects.

  • 4. A subclass must override all abstract methods of the interface before it can be instantiated. Otherwise, the subclass is an abstract class.

1.3.1 Case Code 2

Example

/** Characteristics of interface members: * Can only have abstract methods * Can only have constants * Methods are modified with public & abstract by default * Methods can only be modified with public & abstract * Member variables are modified with public static final by default * * Suggestion: It is recommended to manually add the default modifiers. * * Note: * An interface cannot create objects (cannot be instantiated) * The relationship between a class and an interface is implementation. 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 Relationship Between Interfaces and Classes

  • A: Between classes: inheritance relationship. A class can directly inherit only one parent class, but supports multi-level inheritance.
  • B: Between classes and interfaces: only implementation relationship. A class can implement multiple interfaces.
  • C: Between interfaces: only inheritance relationship. An interface can inherit multiple interfaces.

1.4.1 Case Code 3

Example

/** * Class vs. Class: inheritance relationship, single inheritance, multi-level inheritance * Class vs. Interface: implementation relationship, multiple implementation * Interface vs. Interface: inheritance relationship, 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 The Idea of Interfaces

Earlier we learned the code representation of interfaces. Now let's learn the idea behind interfaces, and then explain with examples from daily life.

For example: We all know that a computer has many ports, and these ports can have corresponding devices plugged into them. Why can these devices be plugged in? The main reason is that these devices conformed to the usage rules of the port when they were produced; otherwise, they could not be plugged into the port, let alone be used. It turns out that the existence of these ports allows us to use more devices.

The emergence of interfaces facilitates later use and maintenance. One side uses the interface (such as a computer), and the other side implements the interface (devices plugged into the port). For example, a laptop uses this rule (interface), and computer peripherals implement this rule (interface).

Interfaces are widely used in the collection framework:

Collection 接口

    List 接口

       ArrayList 实现类

       LinkedList 实现类

    Set 接口

1.6 Advantages of Interfaces

  • 1. The relationship between a class and an interface is implementation, and it is multiple implementation. A class can implement multiple interfaces. The relationship between classes is inheritance. Inheritance in Java is single inheritance; a class can only have one parent class. This breaks the limitation of inheritance.
  • 2. Provide rules to the outside world (USB interface).
  • 3. Reduce the coupling of the program (it enables modular development; once rules are defined, each person implements their own module, improving development efficiency).

1.7 Differences Between Interfaces and Abstract Classes

1. Commonality:Both continuously abstract out methods that are abstract and have no concrete implementation, and neither can be instantiated (objects cannot be created).

2. Differences

1: Relationship with classes

(1) The relationship between a class and an interface is implementation, and it is multiple implementation; a class can implement multiple interfaces. The relationship between a class and an abstract class is inheritance. Inheritance in Java is single inheritance and multi-level inheritance; a class can only inherit one parent class, but it can have a grandparent class.

(2) Difference 2: Members

a.成员变量
    抽象类可以有成员变量,也可以有常量
    接口只能有常量,默认修饰符public static final

b.成员方法
    抽象类可以有抽象方法,也可以有非抽象方法
    接口只能有抽象方法,默认修饰符 public abstract

c.构造方法
    抽象类有构造方法,为子类提供
    接口没有构造方法

1.8 Athlete Case Study

1.8.1 Case Code 4

Example

/** Basketball players and coaches Table tennis players and coaches Now basketball players and coaches are going abroad for a visit and need to learn English. Please use what you have learned to analyze which are classes, which are abstract classes, and which are interfaces.*/ public class InterfaceTest { public static void main(String[] args) { //Create basketball player object BasketBallPlayer bbp = new BasketBallPlayer(); bbp.name = "Yao Ming"; bbp.age = 35; bbp.gender = "Male"; bbp.sleep(); bbp.study(); bbp.speak(); System.out.println("-------------"); //Create table tennis coach object PingpangCoach ppc = new PingpangCoach(); ppc.name = "Fatty Liu"; 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("Eat"); } //sleep public void sleep() { System.out.println("Sleep"); } } //Learn to speak English interface SpeakEnglish { public abstract void speak(); } //Athlete abstract class Player extends Person { //Learn 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("Learn to dunk"); } @Override public void speak() { System.out.println("Speak English"); } } //Table tennis player class PingpangPlayer extends Player { @Override public void study() { System.out.println("Learn to smash"); } } //Basketball coach class BasketBallCoach extends Coach implements SpeakEnglish { @Override public void teach() { System.out.println("Teach dunking"); } @Override public void speak() { System.out.println("Speak English"); } } //Table tennis coach class PingpangCoach extends Coach { @Override public void teach() { System.out.println("Teach smashing"); } }

2. Polymorphism

2.1 Overview of Polymorphism

Polymorphism is the third major characteristic of object-oriented programming, after encapsulation and inheritance.

Real-world things often exhibit multiple forms. For example, a student is a type of person. A specific student, Zhang San, is both a student and a person, thus presenting two forms.

Java, as an object-oriented language, can also describe multiple forms of one thing. For example, if the Student class inherits from the Person class, then a Student object is both a Student and a Person.

2.2 Definition and Usage Format of Polymorphism

The definition format of polymorphism: in fact, it is that a reference variable of the parent class points to a child class object.

父类类型  变量名 = new 子类类型();
变量名.方法名();

A: Format for polymorphism with ordinary classes

父类 变量名 = new 子类();

Such as:

class Fu {}
class Zi extends Fu {}
//类的多态使用
Fu f = new Zi();

B: Format for polymorphism with abstract classes

抽象类 变量名 = new 抽象类子类();

Such as:

abstract class Fu {
    public abstract void method();
}
class Zi extends Fu {
    public void method(){
        System.out.println(“重写父类抽象方法”);
    }
}
//类的多态使用
Fu fu= new Zi();

C: Format for polymorphism with interfaces

接口 变量名 = new 接口实现类();

Such as:

interface Fu {
    public abstract void method();
}
class Zi implements Fu {
    public void method(){
        System.out.println(“重写接口抽象方法”);
    }
}
//接口的多态使用
Fu fu = new Zi();

2.2.1 Case Code

Example

/** Prerequisites for polymorphism: * Inheritance relationship between child and parent classes * Method overriding * Parent class reference points to child class object * * Dynamic binding: the method called during runtime is based on its specific type*/ public class PoymorphicDemo { public static void main(String[] args) { /*Cat c = new Cat(); c.eat();*/ //Parent class reference Animal a //Points to = //Subclass object new Cat() Animal a = new Cat(); a.eat(); } } class Animal { public void eat() { System.out.println("Eating"); } } class Cat extends Animal { public void eat() { System.out.println("Cat eats fish"); } }

2.3 Characteristics of Polymorphic Members

A: Polymorphic member variables

When a member variable with the same name appears in both the parent and child classes, and polymorphism calls this variable:

  • Compile time: it checks whether the class to which the reference variable belongs contains the called member variable. If not, compilation fails.
  • Runtime: it also calls the member variable of the class to which the reference variable belongs.

Simple memory aid: both compilation and runtime reference the left side of the equals sign. Compilation and runtime both look at the left.

B: Polymorphic member methods

  • Compile time: refer to the class to which the reference variable belongs; if the class does not have the called method, compilation fails.
  • Runtime: refer to the class to which the object pointed to by the reference variable belongs, and execute the member method of the class to which the object belongs.

In short: compilation looks at the left, runtime looks at the right.

2.3.1 Case Code Six

Example

/** * Characteristics of polymorphic members: * Member variables compilation looks at the left, runtime looks at the left * Member methods compilation looks at the left, runtime looks at the right * Static methods compilation looks at the left, runtime also looks at the left * * * At compile time, all look at the left; at runtime, member methods look at the right, while others (member variables and static methods) all look at the left **/ public class PoymorphicDemo2 { public static void main(String[] args) { Dad d = new Kid(); //System.out.println(d.num); //d.method(); d.function();//Using a variable to call a static method is actually equivalent to calling it with the class name of the variable's type. } } class Dad { int num = 20; public void method() { System.out.println("I am the parent class method"); } public static void function() { System.out.println("I am the parent class static method"); } } class Kid extends Dad { int num = 10; public void method() { System.out.println("I am the child class method"); } public static void function() { System.out.println("I am the child class static method"); } }

2.4 Upcasting and Downcasting in Polymorphism

Type casting in polymorphism is divided into two types: upcasting and downcasting:

A: Upcasting: when a subclass object is assigned to a parent class reference, it is upcasting. Polymorphism itself is the process of upcasting.

Usage format:

父类类型  变量名 = new 子类类型();

For example:

Person p = new Student();

B: Downcasting: a subclass object that has already been upcast can use the forced type conversion format to convert a parent class reference into a subclass reference. This process is downcasting. If a parent class object is created directly, it cannot be downcast.

Usage format:

Subclass type variable name = (Subclass type) Parent class type variable;

For example:

Student stu = (Student) p;  // 变量p 实际上指向 Student 对象

Example

/** * Upcasting and downcasting in polymorphism: * * Conversion between reference types * Upcasting * From small to large (subtype converted to parent type) * Downcasting * From large to small * Conversion of basic data types * Automatic type conversion * From small to large * byte short char --- int --- long --- float --- double * Forced type conversion * From large to small * * **/ public class PoymorphicDemo3 { public static void main(String[] args) { Animal2 a = new Dog();//Upcasting //a.eat(); Dog d = (Dog)a;//Downcasting d.swim(); } } class Animal2 { public void eat() { System.out.println("Eating"); } } class Dog extends Animal2 { public void eat() { System.out.println("Gnawing bones"); } public void swim() { System.out.println("Dog paddle"); } }

2.5 Advantages and Disadvantages of Polymorphism

Example

/** * Advantages and disadvantages of polymorphism * Advantages: it can improve maintainability (guaranteed by the prerequisites of polymorphism) and improve code extensibility Disadvantages: it cannot directly access members specific to the subclass*/ public class PoymorphicDemo4 { public static void main(String[] args) { MiFactory factory = new MiFactory(); factory.createPhone(new MiNote()); factory.createPhone(new RedMi()); } } class MiFactory { /*public void createPhone(MiNote mi) { mi.call(); } public void createPhone(RedMi mi) { mi.call(); }*/ public void createPhone(Phone p) { p.call(); } } interface Phone { public void call(); } //Xiaomi Note class MiNote implements Phone{ public void call() { System.out.println("Xiaomi Note making a call"); } } //Redmi class RedMi implements Phone { public void call() { System.out.println("Redmi making a call"); } }

Original address: https://www.cnblogs.com/yoke/p/7453864.html