catalogue
The significance of abstract class re implementation in polymorphism
Hello, iron juice ๐!
๐ Today, let's continue to study java and see what abstract classes and interfaces are in Java ๐ค๏ผ
ย
What is an abstract class
๐ We have learned what is a class before. Is abstract class also a kind of class?
It feels so abstract to hear the name! Yes, he is abstract, not concrete. A class that does not contain enough information to describe a specific object is called an abstract class.
ย
๐ฐ Let's take an example of an abstract class
// Abstract classes and methods need to be modified by the abstract keyword abstract class Shape { // Methods in abstract classes are generally required to be abstract methods, which have no method body abstract void draw(); }
People think that this abstract class doesn't do anything, and its only method draw() is still empty.
If a class like this doesn't contain enough information to describe a specific object, it can't instantiate the object. I don't believe you see:
ย
๐ Since a class cannot be instantiated, what is the significance of the existence of this abstract class ๐ค๏ผ Don't worry, existence is reasonable. Listen to me slowly.
ย
The significance of abstract classes in implementing polymorphism
๐ One of the greatest significance of abstract classes is to be inherited. When inherited, you can use abstract classes to realize polymorphism.
Let's look at a piece of code
// Abstract classes and methods need to be modified by the abstract keyword abstract class Shape { // Methods in abstract classes are generally required to be abstract methods, and abstract methods have no method body abstract void draw(); } // When an ordinary class inherits an abstract class, the ordinary class must override the methods in the abstract class class Cycle extends Shape { @Override void draw() { // Override the draw method in the abstract class System.out.println("Draw a circle "); } } public class Test4 { public static void main(String[] args) { //Shape shape = new Shape(); Although abstract classes cannot be instantiated directly // But you can pass an ordinary class object to a reference of an abstract class, that is, the parent class reference points to the child class object Shape shape = new Cycle(); // This is called: upward transformation /*Cycle cycle = new Cycle(); Shape shape = cycle // This is another way of writing upward transformation */ shape.draw(); // Call the method overridden by the subclass through the parent class reference } }
After running, you will find a magical scene:
ย
After reading the code, you may have many questions. Don't worry, let's say one by one,
๐ What is upward Transformation: in a word, the summary is "parent class reference points to child class object"
Changes after upward transformation
- ๐ About methods: the parent class reference can call methods common to the child class and the parent class (if the child class overrides the method of the parent class, the method of the child class will be called), but the method specific to the child class cannot be called.
- ๐ About attributes: parent class references can call the attributes of the parent class, but not the attributes of the child class
The role of upward transformation
- ๐ Reduce some repetitive code
- ๐ When instantiating objects, you can instantiate different objects according to different needs
ย
๐ฐ In this way, we can understand the above code
โย
๐ It seems that we can inherit and rewrite abstract classes through subclasses. Abstract classes are really useful!
๐ But what does this have to do with polymorphism? Abstract classes are so troublesome. I might as well use ordinary classes directly to achieve this effect without writing a subclass ๐ซ๏ผ
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐
๐ฐ Well, if you look at the following code, you will know the benefits of abstract classes in implementing polymorphism.
abstract class Shape { public abstract void draw(); // Abstract methods cannot contain concrete statements } // When an ordinary class inherits an abstract class, the abstract methods in the abstract class must be overridden in this subclass class Cycle extends Shape { @Override // If you don't rewrite it, you will report an error, but if you inherit an ordinary class, you won't report an error. It's safer to use an abstract class public void draw() { System.out.println("Draw a circle "); } } class Flower extends Shape { // Different subclasses override the draw method of the parent class differently @Override public void draw() { System.out.println("Draw a flower"); } } class Square extends Shape { @Override public void draw() { System.out.println("draw a square "); } } public class Test4 { public static void main(String[] args) { Cycle cycle = new Cycle(); // Subclass reference cycle Flower flower = new Flower(); // Subclass reference flower Square square = new Square(); // The type of array is Shape, that is, each element in the array is a parent class reference // In this process, there is also an upward transformation, which rewrites the methods in the abstract class Shape[] shapes = {cycle, flower, square}; // Parent class references refer to different subclass objects for (int i = 0; i < shapes.length; i++) { Shape shape = shapes[i]; // The parent class reference shape points to the current corresponding subclass object shape.draw(); // Call the draw method overridden by the subclass through the parent class reference } } }
๐ Calling the same method printed different results ๐ฎ๏ผ Is this the so-called polymorphism ๐ค
Is it a little confused ๐๏ผ Let's explain ๐
// Add to the above code // Maybe you think about Shape[] shapes = {cycle, flower, square}; I don't quite understand // But the above code is equivalent to ย Shape[] shapes1 = new Shape[3]; // There are three different subclass objects! The array size is 3 // Assigning a subclass reference (pointing to - > subclass object) to the parent class object is not equivalent to the subclass object corresponding to - > pointed to by the husband class reference //This is another way to write the upward transformation. It should be that the subclass object {cycle = new cycle() has been instantiated earlier; ย shapes1[0] = cycle; ย // If the subclass object is not instantiated before, it should be written as shape1[0] = new Cycle ย shapes1[1] = flower; ย shapes1[2] = square;
For polymorphism, it has these three elements
- Inheritance (the Cycle class we just inherited inherits the Shape abstract class)
- Override (our subclass overrides the draw method)
- The parent class points to the child class object (shape1 [0] = cycle -- >, which can also be called upward transformation)
๐ Look back and see if our code is polymorphic ๐.
๐ When our parent class references point to different subclass objects, when we call the same draw method, we output different results. (in fact, the method is rewritten into different forms in subclasses) this is called polymorphism.
Hee hee ๐๏ผ In fact, polymorphism is not so difficult to understand as long as it is combined with examples ๐
ย ย
๐ So why do you have to use abstract classes ๐๏ผ Can I inherit a common class to realize polymorphism ๐ค
๐ฐ Sure, but it's not safe and risky;
ย ย ย ย ย
But if it's an abstract class, it's different ๐
ย ย
๐ From this, we can also see that when using abstract classes, the compiler automatically checks whether we rewrite or not, and making full use of the verification of the compiler is very meaningful in practical development. So the abstract class is still useful, hee hee ๐
๐ Well, I believe you have a general understanding of abstract classes here ๐๏ผ Let's make a brief summary
- A class or method modified with abstract is an abstract class or method
- Abstract classes cannot describe an object concretely and cannot be used to instantiate an object directly
- The member variables and member methods in an abstract class are the same as those in an ordinary class, but they can't be instantiated
- When an ordinary class inherits the abstract class, the ordinary class must override all the abstract methods in the abstract class ๐ค (we said earlier that abstract classes are not specific and do not contain enough information to describe an object, so we need to complete them)
- However, when an abstract class a inherits from abstract class B, it is an abstract class A, so it can not rewrite the abstract methods in abstract class B
- Final cannot modify abstract classes and abstract methods (because the greatest significance of the existence of abstract classes is to be inherited, while those modified by final cannot be inherited. Final and abstraction are natural enemies ๐)
- Abstract methods cannot be modified by private (abstract methods are usually rewritten. How can you rewrite them if you are modified by private ๐ซ)
- Abstract classes do not necessarily have abstract methods, but if a class has abstract methods, then the class must be an abstract class.
๐ฐ Haha, whether the above eight summaries are smelly or not, we don't have to remember them (if we use more, we will remember them naturally) ๐)
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐
What is the interface
๐ Abstract class is a template abstracted from multiple classes. If this abstraction is more thorough, a more special "abstract class" - Interface can be extracted ๐ค.
๐ Interface is one of the most important concepts in Java. It can be understood as a special class. The difference is that the members of the interface have no executor and are composed of global constants and public abstract methods ๐.
How to define an interface? Now let's look at a chestnut ๐ฐ
//The definition format of the interface is basically the same as that of the definition class. By replacing the class keyword with the interface keyword, an interface is defined public interface Interface name{ // Define variables int a = 10; // All member variables in the interface are public static final by default // Abstract method public abstract void method1(); // public abstract is a fixed collocation and can not be written void method2(); // All member methods in the interface are public abstract by default, and the second method is recommended }
You can see that interfaces and classes still have many similarities:
๐ The interface also contains abstract methods, so the interface cannot be instantiated directly ๐ค๏ผ So how do we use interfaces?
๐ Ha ha, it's simple ๐๏ผ Don't we just use a common class to implement this interface ๐๏ผ The difference is that abstract classes are inherited and implemented by subclasses, while interfaces and classes are implemented with the keyword implements.
๐ Just as ordinary classes implement abstract classes, if a class implements an interface, it must implement the abstract methods in the interface, otherwise the class must be defined as an abstract class ๐ค.
Polymorphism through interface
๐ Iron juice! Just now we used abstract classes to realize polymorphism, so now we can try to realize polymorphism with interfaces, hee hee ๐
Interface can be regarded as a special class and can only be used interface Keyword modification interface IShape { int a = 10; The member variables in the interface are all by default public static final int b = 23; void draw(); Generally, member methods in interfaces can only be abstract methods. The default is public abstract(JDK1.8 (before) default void show() { System.out.println("Other methods in the interface");//Other methods in the interface can also be implemented, but they should be decorated with default } public static void test() { System.out.println("This is a static method in the interface"); } } // If an ordinary class wants to implement an interface, it can use implementation, //Because the interface is also an abstract method, the class implementing the interface should also rewrite the abstract method class Cycle implements IShape { @Override public void draw() { System.out.println("Draw a circle "); } } class Square implements IShape { @Override public void draw() { System.out.println("draw a square "); } } class Flower implements IShape { @Override public void draw() { System.out.println("Draw a flower"); } } public class Test4 { public static void main(String[] args) { // IShape iShape = new IShape(); Interfaces cannot be instantiated directly Cycle cycle = new Cycle(); Square square = new Square(); Flower flower = new Flower(); // The IShape interface here is equivalent to the parent class in the abstract class, and the interface type is also a reference type IShape[] iShapes = {cycle, square, flower}; // In fact, this process has undergone upward transformation for (IShape iShape : iShapes) { // The enhanced for each loop can also be written in the form of an ordinary for loop iShape.draw(); // Polymorphism is realized by rewriting } } } Reference variable cycle and square All assigned to Shape Reference variable of type shape, But when executed shape.draw()When, java Who will the virtual machine call to rewrite draw method, It depends on which object the interface refers to at this time shape Yes, or cycle of
๐ Look at the running results ๐
You may feel a little dizzy after reading the code ๐ซ๏ผ But it doesn't matter. General interfaces are not used in this way. It's not good to use abstract classes directly ๐ (I'm just demonstrating that polymorphism can also be achieved with interfaces ๐)
๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐๐
๐ Let's summarize some main features of interfaces in Java
- ๐ฐ Interfaces can contain variables and methods. Variables are implicitly specified as public static final and methods are implicitly specified as public abstract (JDK 1.8 d). A class can implement multiple interfaces at the same time. If a class implements an interface, it must implement the abstract method in the interface. Otherwise, the class must be defined as an abstract class
- ๐ฐ Interfaces support multiple inheritance, that is, an interface can inherit multiple interfaces, which indirectly solves the problem that classes in Java cannot inherit more.
๐ So where is the interface generally used?
- In general, the implementation class and its abstract class have an "is-a" relationship before, but if we want to achieve the same purpose, but there is no such relationship, we can use the interface.
- Due to the single inheritance feature in Java, a class can only inherit one class, but one or more interfaces can be implemented. At this time, interfaces can be used.
๐ฐ Let's take a look at the correct usage of the interface: help java implement "multi inheritance" ๐
because Java Because of the single inheritance feature in, a class can only inherit one class, but can implement one or more interfaces. At this time, interfaces can be used. class Animal { String name; // private cannot be used, and the following subclasses should also be used public Animal(String name) { // Custom constructor of parent class this.name = name; } } interface IFlying { // Customize multiple interfaces void fly(); } interface IRunning { void run(); } interface ISwimming { void swimming(); } // Ducklings can not only run, but also swim and fly A class inherits the parent class and implements multiple interfaces to solve the problem indirectly java Can't inherit more in class Duck extends Animal implements IRunning, ISwimming, IFlying { public Duck(String name) { // Subclass construction method super(name); // Must be on the first line of the subclass constructor // Before giving the construction method of the implementation subclass, first use super() to call the construction method of the implementation parent class. It is compared that there is a parent before a child! // Because the parent class defines its own construction method, the compiler will not automatically add super() to the subclass construction method; To implement the construction method of the parent class, we need to implement it ourselves } // Rewrite the abstract method in the interface @Override public void fly() { System.out.println(this.name + "Flying with wings"); } @Override public void run() { System.out.println(this.name + "Running on two legs"); } @Override public void swimming() { System.out.println(this.name + "Floating on the water"); } } public class Use of interfaces { // Don't learn. I use the Chinese name as the class name. I'm just for the convenience of demonstration public static void main(String[] args) { Duck duck = new Duck("The first duckling"); // Instantiate duck object duck.fly(); // Variable name by reference The method name outputs the rewritten method duck.run(); duck.swimming(); } } Some people may say why use the interface. I'm directly in the parent class Animal Medium implementation fly,run,swimming These properties, Then different animal subclasses inherit the parent class. Can't these methods? But the problem is, ducks will fly,swimming๏ผCan the cat fly and swim? Can't you write a subclass of other animals What about the interface? We just abstract this behavior of flying and swimming, As long as a subclass has this behavior, it can implement the corresponding interface, which is more flexible
๐ The above code shows the most common usage in Java object-oriented programming: a class inherits a parent class and implements multiple interfaces at the same time.
๐ The meaning of inheritance expression is is - a semantics, while the meaning of interface expression is xxx. The class that can implement the interface and the interface do not necessarily have is_a, as long as the class has the characteristics of this interface
Cat is a kind of animal, which can run
Frog is also an animal. It can run and swim
Duck is also an animal. It can run, swim and fly
๐ What are the benefits of this design? Keep the benefits of polymorphism in mind and let the program forget the type With the interface, the user of the class does not have to pay attention to the specific type, as long as the class has this feature.
Take a chestnut ๐ฐ
class Robot implements IRunning { private String name; public Robot(String name) { this.name = name; } // Override the run method @Override public void run() { System.out.println("robot" + this.name + "Running"); } } public class Test4 { public static void main(String[] args) { Robot robot1 = new Robot("Tutu"); robot1.run(); } } // results of enforcement Robot Tutu is running
๐ As long as he can run, whether he is a robot or an animal ๐๏ผ Is the interface very flexible!
At the same time, in the actual development process, generally speaking, a class is a Java file, and an interface is also a Java file. We should also form this good habit at ordinary times!
Ha ha, I wonder if your understanding of abstract classes and interfaces has risen to a higher level? Hee hee, goodbye to our next blog. In the next blog, let's take a look at the commonly used interfaces in Java ๐
Make a little progress every day, iron juice, come on ๐๐๐