[JAVA] Why implement an abstract class (Abstract)

I wasn't quite sure about the benefits of implementing an abstract class, so I've summarized what an abstract class is and what it's intended to do (with what benefits).

Contents of this article

--What is an abstract class? --What makes you happy when you implement an abstract class? --Template Method pattern (design pattern that uses abstract classes) --Template Method Pattern implementation example

What is an AbstractClass?

An abstract class is a class ** that has one or more abstract methods. Abstract classes have no meaning on their own and only work when they are inherited by subclasses.

abstract class class name{
Abstract method
}

So what is an abstract method?

An abstract method is a method written in the following form.

abstract class class name{
abstract Return type Method name(Argument type Argument);
}

As mentioned above, an abstract method defines only the return type, method name, argument type, and number of arguments after abstract, and has no implementation. The concrete implementation is implemented in a subclass that inherits from this abstract class.

Abstract class features

  1. Subclasses that inherit from the abstract class must override the abstract methods in the abstract class
  2. You must write the constructor in a subclass
  3. Cannot be instantiated directly
  4. Multiple inheritance is not possible

Intent to implement an abstract class

The merit of implementing an abstract class is * "A subclass that inherits an abstract class must override the abstract method in the abstract class" * described in Feature 1 of the abstract class.

The specific benefits this means are ... ** You can create implementation-level rules when developing with multiple people! **is. Even so, I don't think you can honestly understand this merit unless you experience large-scale development in a company. (I didn't understand at all: umbrella :)

Now, let's assume that we are doing large-scale development (development with multiple people and the amount of code is thousands to hundreds of thousands of lines), and we will add simple functions and screens to the program. Let's say you need to fix it.

In the case of a simple function addition, the logic of the method is a little different, but in many cases what you want to do is roughly the same as the class you have already implemented. In such a case, if the method name is different depending on the class even though the same processing is performed, it may take time to grasp what processing is being performed: severe:

By making sure that it is written by forced override, which is a feature of abstract classes, the following effects can be obtained: sparkles :: sparkles:

--Unify method names, standardize logic, and make it easier to understand what you are doing. --It is no longer necessary to write common processing to all classes, making it easier to add individual processing. --When the developer defines a subclass, if you forget to implement the method or make a mistake in the method name, a compile error will occur and prevent coding mistakes.

By implementing an abstract class, you can ** create implementation-level rules when developing with multiple people **! !! This is one of the reasons and intent to implement an abstract class.

Next, I will introduce design patterns and sample programs that use abstract classes.

What is the Template Method pattern?

Template Method is a design pattern that uses an abstract class to define the processing framework in a superclass and the specific contents in a subclass.

Characters of Template Method

--The role of Abstract Class --Declare the template method as an abstract method --The role of Concrete Class --Specifically implement the abstract method declared in AbstractClass

Template Method implementation example

For the sake of clarity, it is a very simple sample program that just outputs the log. The Player class plays the role of AbstractClass in the characters of Template Method, and the MusicPlayer class and VideoPlayer class play the role of ConcreteClass. The class diagram is as follows.

Player.png

Let's take a look at the program. First, the superclass Player has three abstract methods: The concrete implementation of the abstract method is done in each of the subclasses MusicPlayer and VideoPlayer.

public abstract class Player {
    abstract void read();
    abstract void write();
    abstract void Playback();
}

And the MusicPlayer class and VideoP class that inherit from Player each override all the abstract methods in the Player class and describe the processing contents. The processing content can be divided into subclasses as shown below. In other words, even if the inherited method name is the same, the processing content can be changed for each inherited subclass. The subclasses MusicPlayer and VideoPlayer are as follows.

public class MusicPlayer extends Player {

   
    @Override
    void read() {
        Log.d("Music Player","read");
    }

    @Override
    void write() {
        Log.d("Music Player","write");
    }

    @Override
    void playback() {
        Log.d("Music Player","playback");
    }
}
public class VideoPlayer extends Player {

    @Override
    void read() {
        Log.d("Video Player","read");
    }

    @Override
    void write() {
        Log.d("Video Player","write");
    }

    @Override
    void palyback() {
        Log.d("Video Player","playback");
    }
}

Finally, the main class. Here is the point!

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MusicPlayer musicplayer = new MusicPlayer();
        VideoPlayer videoplayer = new VideoPlayer();

        Player[] player = {musicplayer,videoplayer};
        for(int i=0; i<player.length; i++) {
            player[i].read();
            player[i].write();
            player[i].playback();

        }

    }

}

In the main class, you put the MusicPlayer instance and the VideoPlayer instance together in one Player array. Then it is turned in a for loop to call three methods. In this part, the point is that the instance stored in player [i] does not check the subclass type with instanceof etc .: point_up:

This is possible because there is a common superclass called Player. In this way, "making sure that any subclass instance assigned to a superclass type variable works correctly" is a general principle of inheritance, not limited to the Template Method pattern. So-called ** polymorphism **.

What if you didn't use the Template Method pattern? MusicPlayer and VideoPlayer will have to be separated and instantiated separately for each class.

In other words Introducing an abstract class ** allows you to assign instances of other subclasses (MusicPlayer and VideoPlayer) to a reference variable of one superclass (Player), so you can use a unified description method for each. You can call the override method of! I'm happy that ** (^^): white_sun_small_cloud:

at the end

I wrote about why I implement an abstract class, partly because I wasn't sure. Implementing an abstract class increases the amount of code and complicates the structure, so it is not desirable to implement an abstract class for anything, but it has such advantages. I would be happy if you could convey.

I also introduced a design pattern called Template Method that uses abstract classes and an implementation example, but I would be grateful if you could point out any mistakes.

Recommended Posts

Why implement an abstract class (Abstract)
java (abstract class)
[java] abstract class
Why java allows final class A {abstract class B {}}
About java abstract class
Interface / abstract class / override
Java learning memo (abstract class)
Create an immutable class with JAVA
Why are class variables needed? [Java]
Difference between interface and abstract class