[JAVA] Object-oriented programming

Classes and instances (object oriented)

Classes are grouped, and instances are defined by grouping rules. The image is like creating an instance called Prius from the class called car.

The essence of object orientation is to make things and use them to create mechanisms. When making things, make them concretely, and when using them, use them while understanding them abstractly.

What to do in class

Define variables and functions that an instance should have. It also describes how to make initial settings when creating an instance. → Define a constructor function so that you can get an argument and create an initial value. → Pass a value as an argument when creating an instance and enter the initial value of the variable in each instance.

class Person {

 private Stirng name; //Here, the variables required for the instance are prepared.
 
 Person(String name, ...) { ////()You can put the necessary arguments inside. Various initial settings for creating an instance are written...
 }

 public void detailData() { //Here the functions required for the instance are written
 }
}
Supplement

-This written in the class means the created instance itself.

private Stirng name; //Define a variable called name in this class

public void nameInput(String input) { //When nameInpu t is executed with the string variable input as an argument
 this.name = input;  //The variable name of this instance will be the same value as the received input.
}

-There are variables for instances (instance feed), but there are also variables for classes (class feed). Since the class feed is a variable in the class, it may be changed every time something happens (eg, every time an instance is created).

Person.Java


class Person {

 private static int count;  //This is a variable for the class
 private Stirng name; //This is a variable for the instance

 Person(String name, ...) { ////Initial settings for instance creation
 Person.count ++; //Now every time a Person instance is created, the count of the Person class will be+1 to be
 }
} 

Call it with a class name.class variable (when used outside the class) or with a self.class variable (when used inside a class)

Initialization, constructor method

This is a function required to receive arguments and set initial values when creating an instance (rather, an initialization function, which is activated every time this class is used !?). However, there is more than one type of argument input pattern for initial value setting. For example, a person with a middle name has more items to enter than a normal person. Therefore, we also need an input function for people who have a middle name. ↓ The constructor method also provides a pattern depending on the input pattern of the argument. You can create a constructor method with the same name that corresponds to multiple argument input patterns by a method called overload.

Person.Java


class Person {

 private Stirng firstname; //Here, the variables required for the instance are prepared.
 private Stirng lastname;
 private Stirng middlename;

 Person(String firstname, String lastname) { //Initial settings for people with only first name and last name
 this.firstname = firstname; //The value of firstname, which is the string used for the argument, becomes the firstname of this instance. The first names shown on the left and right are different.
 this.lastname = lastname;
 }
//Write a function with the same name
 Person(String firstname, String middlename, String lastname) { //Initial settings for firstname, lastname, and middlename people
 this.firstname = firstname;
 this.lastname = lastname;
 this.middlename = middlename;
 }
}

overload and override

overload When overload creates multiple functions with the same name, the input pattern of the argument is different even if the name is the same, so select the most suitable function from that pattern. It is often done mainly for default functions. ↓ When creating the initialization function, the processing contents of the functions created by overload may be duplicated. ↓ For example, there is a function A, which is an initialization function. If you implement this (name etc.) in function A It searches for the initialization function with the same name as function A, searches for function B that processes name in it, and processes name. The code below cleans up the previous code.

Person.Java


class Person {

 private Stirng firstname; //Here, the variables required for the instance are prepared.
 private Stirng lastname;
 private Stirng middlename;

 Person(String firstname, String lastname) { 
 this.firstname = firstname; //The value of firstname, which is the string used for the argument, becomes the firstname of this instance. The first names shown on the left and right are different.
 this.lastname = lastname;
 }

 Person(String firstname, String middlename, String lastname) { //Initial settings for firstname, lastname, and middlename people
 this(firstname, lastname); //This has changed. First that exists in the function with the same name,Processed lastname.
 this.middlename = middlename;
 }
}

override override overrides the contents of the child class when defining a function with the same name as the parent class. ↓ If a function with the same name as a function of a parent class is normally defined in a child class, the function does not inherit the processing contents of the parent class and executes only the processing contents of the child class. ↓ If you want to inherit the processing contents of the parent class to the function of the child class, you have to name the super. Method in the function of the child class.

Person.Java


class Person {
 .
 .
 .

 public void detailData() { //A function that displays detailed information about an instance
 System.out.println("Name is" + this.name); //View instance variables
 System.out.println("Age is" + this.age);
 }
} 

Child.Java


class Child extends Person { //Child class inherits Person class
 .
 .
 .

 public void detailData() { //There is a function with the same name in the parent Person class
 super.detailData(); //Now detailData in the parent Person class()Can take over the processing contents of
 //Write the processing content specific to the child class from here
 .
 .
 }
} 

Encapsulation

Encapsulation is to make things that are easy to understand without waste. When using it, do not show information such as the internal structure so that it can be used while understanding it abstractly (you can use it without thinking about difficult things).

I will write one function in encapsulation here.

It limits the access circuit to variables and functions defined in a certain class (for security?) ↓ When defining variables and functions, you can restrict access by adding this immediately before. ・ Public → Can be accessed from external classes. ・ Private → Cannot be accessed from external classes. It is possible to access using the method inside the class that defines the variable and function. ・ Protected → Basically, it is impossible to access from external classes like private. However, any child class that inherits the class that defines the variable or function can be accessed.

Manners

-Make the variable of the class that is the information of the instance private, and make the function of the class that is the instruction of the instance public so that it can be accessed from the outside. By defining functions (eg get ~ () and set ~ ()) that get and change variables in the class, it is possible to get and change the variables of the instance.

House.Java


class House{

 private Stirng name; //The necessary variables are prepared here.
 private Person owner; //You can store an instance of another class Person in a variable called owner.

 House(String name, ...) { //Instance initialization
 }

//The function is written from here.
 public setOwner(Person person) { //Take the variable person, which is an instance of the Person class, as an argument
  this.owner = person; //The owner of this instance will be the same as the entered variable person.
 }

 public getOwner() {
  return this.owner; //Returns the owner information for this instance. Nothing is displayed by itself because it only returns information
 }
}
Namespace (This is a PHP example, I'm sorry)

Namespaces are used when reading classes, functions, and variables elsewhere (require, include). At that time, if there are the same names of classes, functions and variables, an error will occur. Therefore, I dare to create a parent existence on top of classes, functions, and variables. That is the namespace. References are [Introduction to PHP] Easy-to-understand explanation of how to use namespaces / use!

Class inheritance (parent class, child class)

You can use extend to create a child class that inherits from the parent class. You can also change the initial values of variables and the settings of initial functions for instances in the child class. You can inherit as many classes as you like, so you can create a class of a class of a class.

Manners

-Basically, the file is divided for each class to make it easier to read. -Although it may be different from inheritance, you can load external libraries and packages by importing.

Abstract class

When there is a function that is required for various child classes, but the processing content differs depending on the class. ↓ Define an abstract method (a function that does not dare to write anything) in the parent class. Then, in the child class, you must always override and define the function. A class that has an abstract method is called an abstract class, and you cannot create an instance of that class itself.

Multiple inheritance

Although prohibited in java, inheriting multiple parent classes by a child class is called multiple inheritance.

Fellowship between classes

Another B class instance can be defined as a variable within the A class. For example, in the House class, you can associate an instance of the Person class as a variable owner that indicates the owner.

House.Java


class House{

 private Stirng name; //The necessary variables are prepared here.
 private Person owner; //You can store an instance of another class Person in a variable called owner.

 House(String name, ...) { //()You can put the necessary arguments inside. Various initial settings for creating an instance are written...
 }

//The function is written from here.
 public setOwner(Person person) { //Take the variable person, which is an instance of the Person class, as an argument
  this.owner = person; //The owner of this instance will be the same as the entered variable person.
 }

 public getOwner() {
  return this.owner; //Returns the owner information for this instance. Nothing is displayed by itself because it only returns information
 }
}

Person.Java


class Person {
 private Stirng name; //The necessary variables are prepared here.

 Person(String name, ...) { //()You can put the necessary arguments inside. Various initial settings for creating an instance are written...
 }
//The function is written from here.
 public void detailData() { //Show detailed information about the instance here
 }
}

Main.Java


house1 = New House("A house", ...);
person1 = New Person("Yamamoto", ...); //Take arguments and create an instance of each class

house1.setOwner(person1); //The owner of house1 is now the same as the value of person1.
house1.getOwner().detailData(); //This will give you detailed information about the owner of house1.
//Return owner information with getOwner(Nothing is displayed by itself).. After that, the owner information can be known by using the function defined by Person.
Putting an instance in a variable

Create an instance with new. It receives the value of the argument, reserves an area in memory for that instance, and stores the instance information there. (Information is written in binary) ↓ Assign it to a variable. When you create a variable for an instance, the area for that variable is allocated in memory. Only information about where the instance area is located is left in that area.

Polymorphism

Does it feel like an instance of B class that inherits A class can be treated as an instance of A class or an instance of B class? ..

For example, when executing the same function processing on an instance of another class, it is easy to set a function for each class. However, if the different classes inherit from a common parent class, you only need to write the function processing for that parent class. As a result, even if the number of child classes that inherit the parent class increases, it is not necessary to write function processing.

Code that tends to be done

House.Java


class House {
 .
 .
 .

 public setOwner(Person person) { //Take the variable person, which is an instance of the Person class, as an argument
  this.owner = person; //The owner of this instance will be the same as the entered variable person.
 }
}

Villa.Java


class Villa { //villa means villa
 .
 .
 .

 public setOwner(Person person) { //Take the variable person, which is an instance of the Person class, as an argument
  this.owner = person; //The owner of this instance will be the same as the entered variable person.
 }
}

Person.Java


class Person { 
 .
 .
 .

 public void buy(House house) { //If you receive the variable house, which is an instance of the House class, as an argument
  house.setOwner(this); //This instance is the owner of the variable house.
 }

 public void buy(Villa villa) { //If you receive the variable villa which is an instance of Villa class as an argument
  villa.setOwner(this); //This instance is the owner of the variable villa.
 }
}
Code that takes advantage of polymorphism

(The common parent class of House class and villa class is Building class)

Person.Java


class Person { 
 .
 .
 .

 public void buy(Building building) { //If you receive a variable building that is an instance of the Building class as an argument
  building.setOwner(this); //This instance is the owner of the variable building.
  //If you define a function for the parent class, you don't need to define it for the child class.
 }
}

SOLID An important idea in object orientation. I referred to the following. [What is the object-oriented design principle](https://qiita.com/UWControl/items/98671f53120ae47ff93a#%E4%BE%9D%E5%AD%98%E9%96%A2%E4%BF%82%E9% 80% 86% E8% BB% A2% E3% 81% AE% E5% 8E% 9F% E5% 89% 87)

[[Uncle Bob's Clean Architecture Summary] Object Oriented ~ SOLID Principle ~](https://qiita.com/yoshinori_hisakawa/items/25576a62123607a696f6#%E3%82%A4%E3%83%B3%E3%82%BF % E3% 83% BC% E3% 83% 95% E3% 82% A7% E3% 83% BC% E3% 82% B9% E5% 88% 86% E9% 9B% A2% E3% 81% AE% E5 % 8E% 9F% E5% 89% 87-ispinterface-segregation-principle)

I got a better understanding of Laravel and object-oriented and clean architecture.

Single Responsibility Principle The idea that the definition of a function must be completed in that class.

Open-Closed Principle In short, every class is class-independent, interface-independent.

Let's stop creating (new) an instance of class B directly in class A, because it is difficult to maintain.

Then what do you do? Solved by a design pattern called Factory method. First, create a B_Factory class that has a function that creates an instance of class B and returns it. ↓ Class A uses the B_Factory class to indirectly get an instance of class B.

Liskov Substitution Principle Trying to make it work where the parent class is used, even if the child class is used. In other words, the child class cannot define the properties and methods that the parent class has.

Interface Segregation Principle For maintainability, the class will depend on the interface, but if one interface is too large, the range of influence will be large, so let's make it smaller.

Dependency Inversion Principle Similar to Open-Closed Principle? The upper class should not depend on the implementation of the lower class. A class (eg car) that uses an instance of a class different from the higher level here. A class in which an instance of your class is used from a class other than the lower class (eg engine).

This solution is the same as the Open-Closed Principle and is done by the Factory method.

Other supplements

Magic method (php)

__set and __get. $ obj-> name = value; When you do, __set is activated → Here, you can substitute by using the property name and value as arguments. You can also access private properties. __get is activated by $ obj-> name; → You can get the value by specifying the property name.

Class variables, methods

Static variables and methods are static, so it feels like variables and methods exist in the class itself. The advantage is that it can be read by the class name :: method, so it can be used without an instance.

interface

An interface is a thing that has some abstract methods. Abstract classes are not allowed to be inherited multiple times, but the interface allows them to be inherited multiple times. Also, the abstract methods included in the inherited interface must be overridden and defined.

References that I used as a reference

[What I learned after fighting object-oriented for 10 years] (https://qiita.com/tutinoco/items/6952b01e5fc38914ec4e)

[What is the object-oriented design principle](https://qiita.com/UWControl/items/98671f53120ae47ff93a#%E4%BE%9D%E5%AD%98%E9%96%A2%E4%BF%82%E9% 80% 86% E8% BB% A2% E3% 81% AE% E5% 8E% 9F% E5% 89% 87)

[[Uncle Bob's Clean Architecture Summary] Object Oriented ~ SOLID Principle ~](https://qiita.com/yoshinori_hisakawa/items/25576a62123607a696f6#%E3%82%A4%E3%83%B3%E3%82%BF % E3% 83% BC% E3% 83% 95% E3% 82% A7% E3% 83% BC% E3% 82% B9% E5% 88% 86% E9% 9B% A2% E3% 81% AE% E5 % 8E% 9F% E5% 89% 87-ispinterface-segregation-principle)

I got a better understanding of Laravel and object-oriented and clean architecture.

Recommended Posts

Object-oriented programming
Object-oriented programming terminology
What is object-oriented programming? ~ Beginners ~
Object-oriented summary
Object-oriented rock-paper-scissors
[Java] Object-oriented
Summary of object-oriented programming using Java
Programming learning day 3
Basic Programming Resources
java programming basics
Object-oriented FizzBuzz (Java)
[Java] Object-oriented summary_Part 1
[Processing x Java] Data type and object-oriented programming
[Java] Object-oriented syntax-Constructor
Object-oriented (Java) basics
java Generic Programming
Object-oriented numerical calculation
Organize programming terms
What is programming?
[Java] Object-oriented summary_Part 2
Recommended programming language
Awareness of object-oriented programming for half a year
[Java] Object-oriented syntax-Package
"Inheritance" that even beginners of object-oriented programming can understand
[# 2 Java] What is object-oriented programming that you often hear?
Polymorphism that even beginners of object-oriented programming can understand