JAVA Foundation-Chapter 10 Interface, Polymorphism

Today's content


Three major characteristics of interface -polymorphic
reference type conversion

teaching objectives

Write the format that defines the interface.
Write the format that implements the interface.
Tell the characteristics of the members in the interface. Be
able to tell the prerequisites for using polymorphism.
Understand the upward transformation of
polymorphism. Understanding the downward transformation of polymorphism
can complete the laptop case (method parameters are interface)

Chapter One Interface

1. 1 Overview

An interface is a reference type in the Java language and a collection of methods. If the inside of a class encapsulates member variables, construction methods, and member methods, then
the inside of the interface mainly encapsulates methods, including abstract methods (JDK 7 and before ), default methods and static methods (JDK 8), private methods
(JDK 9).

The definition of an interface is similar to the way of defining a class, but the interface keyword is used. It will also be compiled into a .class file, but it must be made clear that it is
not a class, but another reference data type.

引用数据类型:数组,类,接口。

The use of interface, it can not create objects, but can be implemented (implements, similar to being inherited). A class that implements an interface (it can be regarded as
a subclass of an interface) needs to implement all the abstract methods in the interface. Create an object of this class and then call the method, otherwise it must be an abstract
class.

1. 2 define format

public interface 接口名称 {
// 抽象方法
// 默认方法
// 静态方法
// 私有方法
}

Contains abstract methods

Abstract method: Use abstract keyword modification, can be omitted, there is no method body. This method is used by subclasses.

code show as below:

Contains default methods and static methods

Default method: use default modification, can not be omitted, for subclass to call or subclass to override.

Static method: Use static modification for direct call of the interface.

code show as below:

Contains private methods and private static methods

Private method: Use private to modify, for the default method or static method in the interface to call.

code show as below:

1. 3 basic implementation

Implementation overview

The relationship between the class and the interface is the realization relationship, that is, the class implements the interface. This class can be called the realization class of the interface or the subclass of the interface. Action class implemented

Like inheritance, the format is similar, but the keywords are different, the implementation uses the implements keyword.

Non-abstract subclasses implement interfaces:

1. 必须重写接口中所有抽象方法。
2. 继承了接口的默认方法,即可以直接调用,也可以重写。

Implementation format:

public interface InterFaceName {
public abstract void method();
}
public interface InterFaceName {
public default void method() {
// 执行语句
}
public static void method 2 () {
// 执行语句
}
}
public interface InterFaceName {
private void method() {
// 执行语句
}
}

Use of abstract methods

All must be implemented, the code is as follows:
define interface:
define implementation class:
define test class:
use of default method
can be inherited, can be rewritten, choose one of two, but can only be called by the object of the implementation class.

1. Inherit the default method, the code is as follows:

class 类名 implements 接口名 {
// 重写接口中抽象方法【必须】
// 重写接口中默认方法【可选】
}
public interface LiveAble {
// 定义抽象方法
public abstract void eat();
public abstract void sleep();
}
public class Animal implements LiveAble {
@Override
public void eat() {
System.out.println("吃东西");
}
@Override
public void sleep() {
System.out.println("晚上睡");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
// 创建子类对象
Animal a = new Animal();
// 调用实现后的方法
a.eat();
a.sleep();
}
}
输出结果:
吃东西
晚上睡

Define the interface:

Define the implementation class:

Define the test class:

2. Rewrite the default method, the code is as follows:

Define the interface:

Define the implementation class:

Define the test class:

public interface LiveAble {
public default void fly(){
System.out.println("天上飞");
}
}
public class Animal implements LiveAble {
// 继承,什么都不用写,直接调用
}
public class InterfaceDemo {
public static void main(String[] args) {
// 创建子类对象
Animal a = new Animal();
// 调用默认方法
a.fly();
}
}
输出结果:
天上飞
public interface LiveAble {
public default void fly(){
System.out.println("天上飞");
}
}
public class Animal implements LiveAble {
@Override
public void fly() {
System.out.println("自由自在的飞");
}
}

Use of static methods

Static is related to the .class file and can only be called by the interface name, not by the class name of the implementation class or the object of the implementation class. The code is as follows:

Define the interface:

Define the implementation class:

Define the test class:

Use of private methods

Private method: Only the default method can be called.

Private static methods: default methods and static methods can be called.

If there are multiple default methods in an interface, and there are duplicate content in the methods, they can be extracted and encapsulated in private methods for default methods

Go call. From a design perspective, private methods are an aid to default methods and static methods. Students can test by themselves based on the technology they have learned

test.

Define the interface:

public class InterfaceDemo {
public static void main(String[] args) {
// 创建子类对象
Animal a = new Animal();
// 调用重写方法
a.fly();
}
}
输出结果:
自由自在的飞
public interface LiveAble {
public static void run(){
System.out.println("跑起来~~~");
}
}
public class Animal implements LiveAble {
// 无法重写静态方法
}
public class InterfaceDemo {
public static void main(String[] args) {
// Animal.run(); // 【错误】无法继承方法,也无法调用
LiveAble.run(); //
}
}
输出结果:
跑起来~~~

1.4 Multiple implementations of the interface

As I learned before, in the inheritance system, a class can only inherit one parent class. For interfaces, a class can implement multiple interfaces, which is called access

More realization of the mouth. Moreover, a class can inherit from a parent class and implement multiple interfaces at the same time.

Implementation format:

[]: Indicates optional operation.

Abstract method

When there are multiple abstract methods in an interface, the implementing class must rewrite all abstract methods. If the abstract method has the same name, it only needs to be rewritten once. Code like

under:

Define multiple interfaces:

Define the implementation class:

public interface LiveAble {
default void func(){
func 1 ();
func 2 ();
}
private void func 1 (){
System.out.println("跑起来~~~");
}
private void func 2 (){
System.out.println("跑起来~~~");
}
}
class 类名 [extends 父类名] implements 接口名 1 ,接口名 2 ,接口名 3 ... {
// 重写接口中抽象方法【必须】
// 重写接口中默认方法【不重名时可选】
}
interface A {
public abstract void showA();
public abstract void show();
}
interface B {
public abstract void showB();
public abstract void show();
}
public class C implements A,B{

Default method

When there are multiple default methods in an interface, the implementation class can be inherited and used. If the default method has the same name, it must be rewritten once. code show as below:

Define multiple interfaces:

Define the implementation class:

Static method

In an interface, static methods with the same name will not conflict, because the static methods can only be accessed through their respective interface names.

Priority issue

When a class inherits a parent class and implements several interfaces, the member method in the parent class has the same name as the default method in the interface, and the child class chooses to execute

The member method of the parent class. code show as below:

Define the interface:

@Override
public void showA() {
System.out.println("showA");
}
@Override
public void showB() {
System.out.println("showB");
}
@Override
public void show() {
System.out.println("show");
}
}
interface A {
public default void methodA(){}
public default void method(){}
}
interface B {
public default void methodB(){}
public default void method(){}
}
public class C implements A,B{
@Override
public void method() {
System.out.println("method");
}
}

Define the parent class:

Define subclasses:

Define the test class:

1. 5 Multiple Inheritance of Interface [Understand]

An interface can inherit another or multiple interfaces, which is similar to inheritance between classes. The inheritance of the interface uses the extends keyword, and the child interface inherits
the method of the parent interface. If the default method in the parent interface has the same name, the child interface needs to be rewritten once. code show as below:

Define the parent interface:

interface A {
public default void methodA(){
System.out.println("AAAAAAAAAAAA");
}
}
class D {
public void methodA(){
System.out.println("DDDDDDDDDDDD");
}
}
class C extends D implements A {
// 未重写methodA方法
}
public class Test {
public static void main(String[] args) {
C c = new C();
c.methodA();
}
}
输出结果:
DDDDDDDDDDDD

Define the subinterface:

Tips:

子接口重写默认方法时,default关键字可以保留。
子类重写默认方法时,default关键字不可以保留。

1. 6 Features of other members

接口中,无法定义成员变量,但是可以定义常量,其值不可以改变,默认使用public static final修饰。
接口中,没有构造方法,不能创建对象。
接口中,没有静态代码块。

Chapter 2 Polymorphism

2. 1 Overview

Introduce

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

In life, for example, the actions of running, kittens, puppies and elephants, run differently. Another example is the movement of flying. Insects, birds and airplanes also fly

are different. It can be seen that the same behavior can be embodied in different forms through different things. Polymorphism describes such a state.

definition

Polymorphism: Refers to the same behavior with multiple different manifestations.

Premise [Key Points]

interface A {
public default void method(){
System.out.println("AAAAAAAAAAAAAAAAAAA");
}
}
interface B {
public default void method(){
System.out.println("BBBBBBBBBBBBBBBBBBB");
}
}
interface D extends A,B{
@Override
public default void method() {
System.out.println("DDDDDDDDDDDDDD");
}
}

1. Inherit or realize [choose one of two]

2. Method rewriting [meaning: no rewriting, meaningless]

3. The parent class reference points to the child class object [format embodiment]

2. 2 manifestations of polymorphism

The format of polymorphism:

Parent type: refers to the parent type inherited by the subclass object, or the parent interface type implemented.

code show as below:

When calling a method in a polymorphic way, first check whether the method exists in the parent class, if not, a compilation error will occur; if so, the subclass rewriting is performed

After the method.

code show as below:

Define the parent class:

Define subclasses:

Define the test class:

父类类型 变量名 = new 子类对象;
变量名.方法名();
Fu f = new Zi();
f.method();
public abstract class Animal {
public abstract void eat();
}
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
}

2. 3 Benefits of Polymorphism

In the actual development process, the parent type is used as the method parameter, and the child object is passed to the method, and the method is called, which can better reflect the expansion of polymorphism

Sex and convenience. code show as below:

Define the parent class:

Define subclasses:

Define the test class:

public class Test {
public static void main(String[] args) {
// 多态形式,创建对象
Animal a 1  = new Cat();
// 调用的是 Cat 的 eat
a 1 .eat();
// 多态形式,创建对象
Animal a 2  = new Dog();
// 调用的是 Dog 的 eat
a 2 .eat();
}
}
public abstract class Animal {
public abstract void eat();
}
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
}
public class Test {
public static void main(String[] args) {
// 多态形式,创建对象
Cat c = new Cat();
Dog d = new Dog();
// 调用showCatEat
showCatEat(c);
// 调用showDogEat

Due to the support of polymorphism, the Animal type of the showAnimalEat method is the parent type of Cat and Dog. The parent type receives subclass objects. Of
course , it can pass the Cat object and Dog object to the method.

When the eat method is executed, polymorphism stipulates that the subclass override method is executed, and the effect is naturally consistent with the showCatEat and showDogEat methods,
so showAnimalEat can completely replace the above two methods.

Not only replacement, but in terms of extensibility, no matter how many subclasses appear later, we don't need to write the showXxxEat method,
it can be done directly by using showAnimalEat.

Therefore, the benefits of polymorphism are embodied in that it can make programming easier and have good extensions.

2. 4 reference type conversion

The transformation of polymorphism is divided into two types: upward transformation and downward transformation:

Upward transition

Up-casting: Polymorphism itself is the process of up-casting from a subclass type to a parent type. This process is the default.

When the parent class reference points to a subclass object, it is an upward cast.

Use format:

Downcast

Downcasting: The process of downcasting from the parent type to the child type. This process is mandatory.

showDogEat(d);
/*
以上两个方法, 均可以被showAnimalEat(Animal a)方法所替代
而执行效果一致
*/
showAnimalEat(c);
showAnimalEat(d);
}
public static void showCatEat (Cat c){
c.eat();
}
public static void showDogEat (Dog d){
d.eat();
}
public static void showAnimalEat (Animal a){
a.eat();
}
}
父类类型 变量名 = new 子类类型();
如:Animal a = new Cat();

For a subclass object that has been upcast, the parent class reference can be converted to a subclass reference. The format of forced type conversion can be used, which is downcast.

Use format:

Why transform

When calling a method using polymorphism, first check whether the method exists in the parent class, if not, a compilation error will occur. In other words, you cannot call subclasses

There are methods that the parent class does not have. Compilation is wrong, let alone running. This is also a little trouble that polymorphism brings us. So, want to call sub

Class-specific methods must be downcast.

Transformation demonstration, the code is as follows:

Define the class:

Define the test class:

Subtype variable name = (subtype type) parent variable name;

如:Cat c =(Cat) a;
abstract class Animal {
abstract void eat();
}
class Cat extends Animal {
public void eat() {
System.out.println("吃鱼");
}
public void catchMouse() {
System.out.println("抓老鼠");
}
}
class Dog extends Animal {
public void eat() {
System.out.println("吃骨头");
}
public void watchHouse() {
System.out.println("看家");
}
}
public class Test {
public static void main(String[] args) {
// 向上转型
Animal a = new Cat();
a.eat(); // 调用的是 Cat 的 eat
// 向下转型
Cat c = (Cat)a;
c.catchMouse(); // 调用的是 Cat 的 catchMouse
}
}

Transformation anomaly

In the process of transformation, you will encounter such problems if you are not careful. Please see the following code:

This code can be compiled, but when it runs, it reports a ClassCastException, a type conversion exception! This is because the
Cat type object is clearly created , and of course it cannot be converted into a Dog object at runtime. These two types do not have any inheritance relationship and do not conform to the definition of type conversion.

In order to avoid the occurrence of ClassCastException, Java provides the instanceof keyword to verify the type of reference variables, the format is as follows:

Therefore, before the conversion, we had better make a judgment first, the code is as follows:

Chapter 3 Comprehensive Cases of Interface Polymorphism

3. 1 laptop

public class Test {
public static void main(String[] args) {
// 向上转型
Animal a = new Cat();
a.eat(); // 调用的是 Cat 的 eat
// 向下转型
Dog d = (Dog)a;
d.watchHouse(); // 调用的是 Dog 的 watchHouse 【运行报错】
}
}
变量名 instanceof 数据类型
如果变量属于该数据类型,返回true。
如果变量不属于该数据类型,返回false。
public class Test {
public static void main(String[] args) {
// 向上转型
Animal a = new Cat();
a.eat(); // 调用的是 Cat 的 eat
// 向下转型
if (a instanceof Cat){
Cat c = (Cat)a;
c.catchMouse(); // 调用的是 Cat 的 catchMouse
} else if (a instanceof Dog){
Dog d = (Dog)a;
d.watchHouse(); // 调用的是 Dog 的 watchHouse
}
}
}

Laptops usually have the function of using USB devices. During production, notebooks are reserved for USB ports that can be inserted into USB devices,
but notebook manufacturers do not care about the specific USB devices, as long as they meet the USB specifications.

Define the USB interface, with the most basic opening and closing functions. If the mouse and keyboard are to be used on the computer, the mouse and keyboard must also comply with the
USB specification and implement the USB interface, otherwise the mouse and keyboard cannot be used when they are produced.

3. 2 case analysis

Describe the notebook class to realize the use of USB mouse and USB keyboard in the notebook

USB interface, including opening and closing functions

Notebook class, including running function, shutdown function, use USB device function

Mouse class, to implement USB interface, and have a click method

Keyboard class, to realize the USB interface, with the method of tapping

3. 3 case realization

Define the USB interface:

Define the mouse class:

Define the keyboard class:

interface USB {
void open();// 开启功能
void close();// 关闭功能
}
class Mouse implements USB {
public void open() {
System.out.println("鼠标开启,红灯闪一闪");
}
public void close() {
System.out.println("鼠标关闭,红灯熄灭");
}
public void click(){
System.out.println("鼠标单击");
}
}

Define the notebook class:

The test class, the code is as follows:

class KeyBoard implements USB {
public void open() {
System.out.println("键盘开启,绿灯闪一闪");
}
public void close() {
System.out.println("键盘关闭,绿灯熄灭");
}
public void type(){
System.out.println("键盘打字");
}
}
class Laptop {
// 笔记本开启运行功能
public void run() {
System.out.println("笔记本运行");
}
// 笔记本使用usb设备,这时当笔记本对象调用这个功能时,必须给其传递一个符合USB规则的USB设备
public void useUSB(USB usb) {
// 判断是否有USB设备
if (usb != null) {
usb.open();
// 类型转换,调用特有方法
if(usb instanceof Mouse){
Mouse m = (Mouse)usb;
m.click();
}else if (usb instanceof KeyBoard){
KeyBoard kb = (KeyBoard)usb;
kb.type();
}
usb.close();
}
}
public void shutDown() {
System.out.println("笔记本关闭");
}
}
public class Test {
public static void main(String[] args) {
// 创建笔记本实体对象
Laptop lt = new Laptop();
// 笔记本开启
lt.run();
// 创建鼠标实体对象

Usb u = new Mouse();
// Use the mouse in the notebook
lt.useUSB(u);

// Create a keyboard entity object
KeyBoard kb = new KeyBoard();
// Use the keyboard for the notebook
lt.useUSB(kb);

// The notebook is closed
lt.shutDown();
}
}

Guess you like

Origin blog.csdn.net/weixin_43419256/article/details/108198515