[JAVA] Copy and paste the source in class development ...? That's NO! Let's know about "inheritance"!

This is the 4th day of Stylez Advent Calendar 2016. In the spring of 2016, I was still a Java beginner and learned about inheritance for the first time ... This is the article I was summarizing at that time.

Basics of inheritance

1. The problem of copying when developing a similar class

If you are writing a large program, you may need to create a class that is similar to the one you created earlier. In such a case, if you copy and paste the original code and add a new function, the following disadvantages will occur.

--It takes time to add / modify --When you add a new method to the copy source class, or when you change the method, you need to add or change the copied class as well. ――It becomes difficult to grasp and manage --There are many duplicates of source code between the copy source class and the copied class. This makes the entire program less visible and difficult to maintain.

2. Resolution by inheritance

A function called ** inheritance ** makes it possible to create similar classes while avoiding the disadvantages that occur when creating similar classes by copy and paste.

Inherit and create class.java


//Class you want to inherit
Public class Hero {
    private String name = "Brave";
    Private int hp = 100;

    //escape
  public void run(){
      System.out.println(name + "Escaped!");
    }
}

//I want to inherit the Hero class and become a stronger hero ...
Public Class SuperHero extends Hero { //Point 1
    public void attack(Matango m){
      System.out.println(name + "Attack!");
      m.hp -= 5;
      System.out.println("Inflicted 5 points of damage!");
      }
}

--Note the ** extends ** on the point 1 line in the code above. By writing SuperHero extends Hero, it means that the definition of the same member as Hero is omitted because the SuperHero class is defined based on the Hero class **.

Defining a class with inheritance.java


Class Class name extends Original class name{
With the parent class"Difference"member
}

--When defining a class that uses inheritance, write the members of the difference, such as the members that you want to add to the parent class (the class that is the source of inheritance), in the child class (the newly defined class). --When the SuperHero class is instantiated, the JVM will determine that the SuperHero class also has a run () for the Hero class.

Therefore, in the SuperHero class that inherits the Hero class, not only the attack () method defined in the SuperHero class but also the run () method of the Hero class can be called.

3. How to express inheritance relationship

In the example, the SuperHero class was created by inheriting the Hero class. The relationship between these two classes is called the ** inheritance relationship **, and the inheritance relationship can be expressed as follows. hero (parent class, super class)superhero (child class, subclass)

4. Inheritance variations

Inheritance can also define many child classes based on one parent class. However, ** It is not possible to define one child class that inherits multiple parent classes (multiple inheritance). ** **

5. Override

When there is a situation where you want to redefine the members defined in the parent class in the child class, you can overwrite the members of the parent class with the child class. It's called ** Override **.

** ◎ Members declared in child classes using inheritance ** (1) If the parent class does not have the same member, that member becomes an "added" member. (2) If the parent class has the same member, that member becomes a member to be "overwritten".

6. Prohibition of inheritance and override

--Classes with final at the time of declaration cannot be inherited.

Classes that cannot be inherited.java


public final class String extends Object....

--Methods with final when declared cannot be overridden in child classes

Methods that cannot be overridden.java


public final void slip()....

The appearance of the instance

SuperHero class created on the basis of inheritance ... This instance contains a Hero instance inside, and has a ** double structure ** as a whole. With this structure in mind, let's understand various calls and operating principles.

1. Method call

--When a method is called from outside the instance, the multi-structured instance tries to ** correspond with the method of the child instance part that is outside as much as possible **. Example) If the method run () matches both the parent class Hero and the child class SuperHero, the call to run () corresponds to SuperHero's run ().

--In the above example, ** Hero's run () method does not work with external calls **

2. Access to the parent instance

--When you need to access the parent instance part, you can access the parent instance part from the child instance part by using ** super **, which is a reserved word that represents the parent instance part.

◎ Use the field of the parent instance part

super.Field name


 ◎ Call the method of the parent instance part

#### **`super.Method name(argument)`**
```Method name(argument)


 --super.run () calls the run () method of the parent instance part, but if you write run (), it has the same meaning as "this.run ()", and run () defined by yourself. Call the method.

 * When three classes, A class (grandparents), B class (parent), and C class (self), have an inheritance relationship, c class can access the parent class B class, but go to A class, which is the grandparent. It cannot be accessed directly.

# Inheritance and constructor
### 1. How to create a class using inheritance
 When creating an instance of the SuperHero class that inherits the Hero class, the SuperHero constructor is called, but in fact, the inherited Hero constructor is also called at this time.
 → ** Java has a rule that "all constructors must call the constructor of the internal instance part at the beginning" **, so this behavior is performed.

 --Originally, you have to write super (argument); on the first line of the constructor.
 --If the programmer forgets to write super (argument) ;, the compiler will automatically add super () ;.

### 2. Situation where the parent instance part cannot be created
 As explained in "1. How to create a class using inheritance", super (); will be added automatically even if you forget to write it.
 However, the automatically generated super (); tries to call the constructor of the parent class with no arguments.

 At this time, if there is no constructor that can be called without an argument in the constructor existing in the parent instance, there is no constructor that can be called and it causes an error.

### 3. Specify the constructor argument of the internal instance.
 The call failed because there was no constructor that could be called with no arguments. What to do ...

 ◎ Specify the argument when calling the constructor.
```public item (string name){ ```
 If you want to call the constructor, you can call the constructor correctly by using an argument like super ("just a bar") ;.
 At this time, pay attention to the type and number of arguments of the constructor to be called.

# Correct inheritance, wrong inheritance
### 1. is-a principle
 Correct inheritance is ** inheritance that follows the rule called "is-a principle" **

 ◎ is-a relationship
 Child class is-a Parent class (child class is a kind of parent class)
 A is-a B means "A is a kind of B"

 Try to make a sentence of is-a when inheriting, and if it is unnatural, the inheritance is wrong.
 ◎ Rules regarding the use of inheritance
 If the principle of is-a does not hold, you should not use inheritance even if you can do it easily.

### 2. Why you shouldn't do the wrong inheritance

 There are two reasons why you should not use inheritance that is not an is-a relationship.

 ――In the future, when you expand the class, there will be a contradiction with the real world.
 ――Because you will not be able to use "diversity", the last of the three major object-oriented functions.

### 3. Generalization / specialization relationship
 Being connected by the is-a relationship means that the child class becomes more specific (specialized) into a "special and concrete thing", and the parent class becomes "general, abstract and ambiguous". It will be generalized (generalized) to "things".

 --If you specialize, you can define fields and methods in detail, and the number of members will increase.
 --Generally, it becomes difficult to define detailed fields and methods.

 Inheritance is both a "tool to reduce duplicate code description" and a tool to "show that two classes have a specialization / generalization relationship".


Recommended Posts

Copy and paste the source in class development ...? That's NO! Let's know about "inheritance"!
[Ruby] Difference between methods with and without self in the class. About class methods and instance methods.
Summary of copy and paste commands used when you want to delete the cache in iOS application development anyway
About next () and nextLine () of the Scanner class
About class inheritance.
About the difference between classes and instances in Ruby
About Class loading and initialization when the JVM starts
[Ruby] Class nesting, inheritance, and the basics of self