[JAVA] Explaining "object-oriented" that even elementary school students can understand in 5 levels

Are there many people who think that writing classes is object-oriented these days? The content is about ** that even elementary school students can understand ** for such people. I will explain object-oriented programming in a self-styled manner with a mixture of subjectivity. Please note that it may be a little difficult to understand because the vocabulary is low.

Level 1 "Thinking in reality"

First of all, I will explain it in a fairly chewy manner. There are various meanings of ** "object" **, but here we will explain with ** "object" **. There are four basic fluctuations in "object": ** "production", "movement", "change", and "destruction" **. These fluctuations have different behaviors depending on the ** nature of the "object" **.

Expressed as a "robot", it is as follows.

-** [Production] Robots are made ** -** [Action] Robot moves forward by command ** -** [Change] Robot deteriorates over time ** -** [Destroy] Robot explodes and disappears **

Next, when expressed in "animals", it is as follows.

-** [Production] Animals are born ** -** [Action] Animal walks forward ** -** [Change] Animals get older ** -** [Destroy] Animals die **

** The essence of fluctuation is similar **, but ** the behavior is completely different **. We will build a framework ** that processes these ** behaviors separately for each property of the thing ** "object-oriented" **.

Level 2 "Game-like way of thinking"

Video games you all know. All the things represented on the screen are ** "objects" **. Let's take a look at the four variations of the basic display in the game.

Object production motion change Destruction
character Appearance Operation, AI behavior Increase / decrease life, level up Exit, death
Text information display Display animation Color, font Hide
background display scroll Color, change over time Hide

The framework for managing these as "objects" is "object-oriented". It can be said that the game itself is "object-oriented". People involved in game development must have an object-oriented understanding in common.

Level 3 "Thinking about commonalities and differences"

In any environment, there are some ** attributes ** that objects have in common.

--Identifier (name, etc.) --Position (three-dimensional)

Let A be these ** common attributes **. Next, let's consider the difference between animals and machines. (Various things can be assumed in the game, but here we will take the real world as an example)

--Voice for animals, electronic sound for machines (makes sounds) ... ① --Animal is the heart, machine is the CPU (active) ... ② --Animal, machine ... etc ...

** I somehow understand that the phenomenon is different, but the essence is the same **. Let's call these differences B. Next, consider ** whether the difference can be judged by appearance **. Pay attention to B ①②.

―― ① Animals make sounds with vocal cords, machines make sounds with speakers ――② Animal heart moves by blood pressure, machine CPU moves by voltage

** The essence is the same, but the mechanism is different. ** ** Let this difference be C.

Level 4 "Three principles of object orientation"

It is said to be the three object-oriented principles ** "inheritance" "polymorphism" "encapsulation" **. As some of you may have noticed, the element ABC explained in Level 3 actually applies to this.

--A: Inherit items of common attributes: ** Inherit ** --B: Polymorphism with the same essence but different behavior: ** Polymorphism ** --C: Mechanism invisible from the outside: ** Encapsulation **

Level 5 "Try to write a program"

I'm finally writing a program, but this time I'll write it in ** C ++-like notation **.

It's long to do it, so I'll try to express it with * "difference between dog and monkey" * that just outputs simple characters. As a premise, the following classes / functions / macros used in the example are explained.

name class/function/macro Description
String class Simplifies string processing.
print function Outputs a character string.
strMarge function Combines two or more strings.
std::shared_ptr std library Use a smart pointer.

Difference between dog and monkey


class Animal{
private:
  String name;
  String voice;
  String food;

protected:
  void init(const String& in_name, const String& in_voice, const String& in_food)
  {
    this->name = in_name;
    this->voice = in_voice;
    this->food = in_food;
  }
  virtual ~Animal() {}

public:
  String getName()  { return this->name;  }
  String getVoice() { return this->voice; }
  String getFood()  { return this->food;  }
  virtual void actionRun(){}  //Overwrite with inheritance destination
  virtual void actionTalk(){} //Overwrite with inheritance destination
  virtual void actionEat(){}  //Overwrite with inheritance destination
};

class Dog : public Animal{
public:
  Dog(){ this->init("dog", "one! one!", "Bone"); }
  virtual void actionRun() override { print(strMarge(this->getName(), "Walks with four legs")); }
  virtual void actionTalk() override { print(strMarge(this->getName(), "Is", this->getVoice(), "Barking")); }
  virtual void actionEat() override { print(strMarge(this->getName(), "Is", this->getFood(), "Eat with a gorigori")); }
};

class Monkey : public Animal{
public:
  Monkey(){ this->init("monkey", "Key! Key!", "banana"); }
  virtual void actionRun() override { print(strMarge(this->getName(), "Walks with limbs")); }
  virtual void actionTalk() override { print(strMarge(this->getName(), "Is", this->getVoice(), "Cry")); }
  virtual void actionEat() override { print(strMarge(this->getName(), "Is", this->getFood(), "Peel and eat by hand")); }
};

int main()
{
  std::shared_ptr<Animal> dog    = std::make_shared<Dog>();
  std::shared_ptr<Animal> monkey = std::make_shared<Monkey>();
  
  dog->actionRun();     //The dog walks with four paws
  dog->actionTalk();    //The dog is one! one! Barking
  dog->actionEat();     //Dogs eat bones

  monkey->actionRun();  //Monkeys walk with their limbs
  monkey->actionTalk(); //The monkey is the key! Key! Cry
  monkey->actionEat();  //Monkeys peel bananas by hand and eat

  return 0;
}

Even if ** type ** is Animal, the output content is different because ** entity (instance) ** is Dog and Monkey. The main points of the above code are summarized in bullet points.

-(1) When declaring each class of Dog and Monkey, ** inherit ** the class Animal that manages common attributes. --At the time of initialization, each common attribute is initialized. -② Override (override) ** three Animal virtual functions in each class and implement the behavior separately. ** (Polymorphism) ** ――③ I called the common method in the main function, but different sentences were output without knowing anything. (Encapsulation)

If ①②③ are completed, ** the object-oriented framework is completed **.

Summary

When it comes to the actual game, each class method written in the level 5 example is It will be a more complicated mechanism with animation changes and status changes rather than simple contents such as character output. Divide the complicated mechanism into classes to hide the behavior from the outside, ** It is possible to improve the implementation speed and implement readable source code naturally **, It's an absolute object-oriented advantage.

Recommended Posts

Explaining "object-oriented" that even elementary school students can understand in 5 levels
What is deployment (maybe even elementary school students can understand it!)
"Inheritance" that even beginners of object-oriented programming can understand
Polymorphism that even beginners of object-oriented programming can understand
Scala's Implicit that even Java shops can understand
Basics of jQuery that even freeters can understand
Android environment construction that even monkeys can understand [React Native]