Jun 01, 2021 Article blog
As a programmer, you're certainly not new to
多态
because you'll see it in languages such as
C++
Java
and
面向对象
多态
is a feature that is often used and very useful in object-oriented categories, and it doesn't matter if you haven't learned it before, let's illustrate it with a simple example.
多态
is mainly used in strong-type languages, such as
Python
such as weak-type languages, variable types can be changed at will, there are no restrictions, in fact, the difference is not very big.
The type of variable is clear when we use variables for
Java
or
C++
B
ut if we want it to be a little looser, let's call the method with a parent class pointer or reference, but at the time of execution, we can execute the method in the subclass based on the type of the child class.
That is to say, to implement a situation where we call up different results or functions in the same way, this is called polymorphism.
(Recommended course: Go tutorial)
To give a very classic example, cats, dogs and people are mammals.
All three classes have a
say
method, we all know that cats, dogs and human
say
are not the same, cats may be barking, dogs are barking, humans are talking.
class Mammal {
public void say() {
System.out.println("do nothing")
}
}
class Cat extends Mammal{
public void say() {
System.out.println("meow");
}
}
class Dog extends Mammal{
public void say() {
System.out.println("woof");
}
}
class Human extends Mammal{
public void say() {
System.out.println("speak");
}
}
This code should not be difficult for everyone to understand, these three classes are
Mammal
Three Classes, assuming that at this time we have a series of instances, all of which are instances of
Mammal
but all three types have, and we want to call them all together in a loop.
Although we receive variables using The parent class type of
Mammal
we get the results of each child class when we call them.
Like this:
class Main {
public static void main(String[] args) {
List<Mammal> mammals = new ArrayList<>();
mammals.add(new Human());
mammals.add(new Dog());
mammals.add(new Cat());
for (Mammal mammal : mammals) {
mammal.say();
}
}
}
Not knowing if you have
get
to the essence, we created a
List
and put instances of its children into it. T
hen a loop is passed to receive the parent class object, and the
say
method is called.
We hope that although we call the method with a reference to the parent class, it can automatically call methods in different subclasses based on the type of the child class.
That is, the result we get should be:
speak
woof
meow
This function is polymorphism, which means that we can define methods in the parent class and create different implementations in the child class. But at the time of the call is still with the reference of the parent class to call, the compiler will automatically do our internal mapping and conversion.
This implementation is certainly feasible, but there is a small problem that the
say
method in the
Mammal
class is overused. B
ecause we're only using its children, we're not going to use
Mammal
So we don't have to implement the
say
method in the parent
Mammal
tag, to indicate that there is such a method, the child class implementation needs to implement it on it.
This is where abstract classes and abstract methods come from, and we can make
Mammal
into an abstract class that
say
to be an abstract method. A
bstract classes can't create instances directly, they can only create instances of subclasses, and abstract methods don't have to be implemented, just mark parameters and return them. S
pecific implementations are carried out in subclasses. T
o put it bluntly, an abstract method is a markup that tells the compiler that any child that inherits the class must implement an abstract method, and that the methods in the parent class cannot be called.
That abstract class is a class that contains abstract methods.
Let's write the code after
Mammal
becomes an abstract class:
abstract class Mammal {
abstract void say();
}
It's simple, because we just need to define the parameters of the method, we don't need to implement the functionality of the method, the functionality of the method is implemented in the subclass.
Since we mark
say
as an abstract method, any subclass that inherits
Mammal
must implement it, or it will be reported incorrectly.
(Recommended course: Go Web programming)
Abstract class is actually a edge ball, we can define abstract methods in abstract classes that only declare not to implement, can also implement concrete methods in abstract classes. I
nstances of non-abstract method subclasses in abstract classes can be called directly, just as children call common methods of parent classes. B
ut what if we don't need a parent-class implementation method, and we propose that all methods in the extracted parent class are abstract?
In this case, there is also a concept in
Java
called interface,
interface
interface
essentially an abstract class, but an abstract class with only abstract methods.
So the
Mammal
can also be written as:
interface Mammal {
void say();
}
After turning The Search
interface
into a
Mammal
the implementation of the subclass is not much different, except that the
extends
keyword is replaced with
implements
I
n addition, subclasses can inherit only one abstract class, but can implement multiple interfaces.
In earlier
Java
of Java,
interface
was only able to define methods and constants, and in later versions of
Java8
we were able to implement some default and static methods in the interface.
The benefits of an interface are obvious, and we can call all the classes that implement it with an instance of the interface. That is to say, the interface and its implementation is a much broader inheritance relationship, greatly increasing flexibility.
Although the above is all
Java
content, but is actually talking about object-oriented content, if you have not learned
Java
small partners may look a little bit hard, but overall the problem is not big, there is no need to fine-button the syntax details,
get
to the core essence on it.
The purpose of such a large paragraph is to clarify some of the concepts in the object-oriented, as well as the use of interfaces and concepts, followed by the main play of this article, that is, the use of interfaces in the
Go
language and ideas.
There are interfaces in
Golang
but its concept and usage methods are slightly different from
Java
and their use scenarios and implementations are similar and essentially abstract.
Some methods have been extracted through the interface, and all the classes that inherited the interface must have these methods, so we can use them by getting instances of these classes through the interface, greatly increasing flexibility.
But one of the big problems with interfaces in
Java
is intrusiveness, which, to put it bluntly, reverses supply and demand. T
o give a simple example, suppose you wrote a crawler crawling content from each page. T
here are many categories of content crawled by reptiles, including pictures, text, and videos. S
uppose you want to abstract an interface in which you define some of the methods you specify for extracting data. T
his way you can use this interface to call, regardless of the format of the data you get. T
his in itself is a scenario for interfaces, but the problem is that the components that handle pictures, text, and video may be open source or third-party, not developed by you.
You define an interface that doesn't work, and someone else's code doesn't inherit it.
Of course, this can also be solved, for example, you can package yourself outside these third-party tool libraries to implement the interfaces you define. Of course it's OK, but it's obviously cumbersome.
(Recommended micro-class: Go micro-class)
The interface in
Golang
solves this problem, which means that it completely removes the already weakened inheritance relationship, so long as the methods defined in the interface can correspond, then this class can be considered to have implemented the interface.
Let's start by creating an
interface
and, of course, through
type
keyword:
type Mammal interface {
Say()
}
We have defined an interface for
Mammal
in which a
Say
function is declared.
That is, as long as the structure that owns this function can be received with this interface, we define
Cat
Dog
and
Human
as we did just now, to implement their respective
Say
methods:
type Dog struct{}
type Cat struct{}
type Human struct{}
func (d Dog) Say() {
fmt.Println("woof")
}
func (c Cat) Say() {
fmt.Println("meow")
}
func (h Human) Say() {
fmt.Println("speak")
}
After that, we try to use this interface to receive objects from various structures, and then call their
Say
method:
func main() {
var m Mammal
m = Dog{}
m.Say()
m = Cat{}
m.Say()
m = Human{}
m.Say()
}
The result, of course, was the same as we had expected:
Today we talked about polymorphisms and interface concepts in object-oriented objects to learn more about why interface design in
golang
is so good because it decouples the connection between interfaces and implementation classes, further increasing the flexibility of our coding and solving the problem of the reversal of supply and demand.
But there is no absolute good or bad in the world, golang interface in the convenience of our coding at the same time also brought some problems, for example, because there is no interface and implementation class strong binding, in fact, also to a certain extent increased the cost of development and maintenance.
Overall, this is a benevolent change, some students who are used to
Java
may feel that it is not necessary, this is excessive untie, some students who have suffered from it may feel that this progress is very critical. B
ut no matter how you look at it, it does not affect us to learn it, after all, learning itself is not a position.
Today's content contains some
Java
and
面向对象
just used to draw out the content of the next
golang
if there is a part of the do not understand the place, I hope you grasp the big and small, understand the core key is good, do not need to buckle every detail.
The above is about the implementation of
Go
language
多态
and
interface
use related to the introduction, I hope to help you.
Source: www.toutiao.com/i6855609145085985287/?group_id=6855609145085985287