[JAVA] A memo for myself that object-oriented is something

It's been a year since I started programming. It's not that I haven't touched it at all because I made an Android app, but I keep thinking that it's object-oriented. If you do not understand it, it will be difficult in the future, so make a note. Written in Java and Ruby

What is written here is a compilation of research by the author who is a super beginner in programming, so I think there are many incorrect notations and meanings.

I would be grateful if you could point out any mistakes.

A little about the class

I made a lot of methods in the Main class! !! I don't know this anymore!

Main.java


class Main{
 public static void main(String[] args){
  hello();
  sorry();
  goodbye();
  fine();
  .
  .
  .
 }
  public static void hello(){
   //Process statement
  }
  public static void sorry(){
   //Process statement
  }
  .
  .
  . 
}

↓ Create other classes and write a lot of methods!

Main.java


class Main{
 public static void main(String[] args){
  Person.hello();
 }
}

Person.java


class Person{
 public static void hello(){
  System.out.println("Hello World");
 }
}

(In Ruby)

index.rb


class Person
 #Contents
end

great! Clean!

What is an object

Represents "things" in the real world (often written in various places) For example, if there is an object called Otaku,

Specs (information) --28 years old --Single --History without her = age --Virgin --Fat

What you can do (behavior) --You can use a PC --Withdrawal in the room --You can talk about anime

Can be explained with the feeling (prejudice)

Objects are also known as instances.

Object = instance!

You need a class to create an instance. In other words, the class is the blueprint of the instance. (It is often written in various places)

Now let's define otaku. It's easy. Just write the "specs" and "what you can do" of the instance in the Otaku class (blueprint).

Let's make Otaku

Main.java


class Main{
 public static void main(String[] args){
   Otaku otaku1 = new Otaku();  //➀ Create an instance of the Otaku class! Instances are assigned to variables and used!
 //Class type variable name(Instance name) =new class name();
   Otaku otaku2 = new Otaku();
   Otaku otaku3 = new Otaku();  //➁ You can create many instances from the same class type! There are a lot of otaku!

   //➃ Instance name.Method name()You can use what Otaku can do!
   otaku1.usePC();  
   otaku1.specBody();  //➄ In the specBody method, "I'm fat!I want to say! Value of instance field body("fat")Want to use!
 }
}

Otaku.java


class Otaku{
 //➂ Here are the specifications of Otaku(information)I'll define! It seems that the instance field is a difficult word? But it's a variable declaration!(maybe!)
 public String age;
 public String body;

 //➂ Assign a value in the constructor!
 Otaku(){
  otaku1.age = "28 years old"; 
  otaku1.body = "fat";
 }  

 //➃ What Otaku can do from here(Behavior)Is expressed by a method! Also called an instance method!
 public void usePC(){
  System.out.println("I'm a big computer teacher!");
 }
 public void specBody(){
  System.out.println("I" * this.body + "is!");  //➄ MainクラスでspecBodyメソッドが呼ばれた時に、thisをインスタンス名に置き換えるよ! これで「Iデブis!You can say!
 }
}

(How to use instance method in Ruby)

otaku.rb


class Otaku
 def usePC  #Instance method definition
   puts "I'm a big computer teacher!"
 end
end

otaku = Otaku.new  #Instance generation
otaku.usePC

public or static

public ・ ・ ・ Can be called from outside the class static ・ ・ ・ Can be called without creating an instance

A little more about the constructor

A constructor is a special method that is automatically called after instantiation using new. Synonymous with "initialize method" in Ruby

If you use the constructor when setting the value of the instance field and not use it, the code will change considerably! Let's remember properly!

No constructor ver

Main.java


class Main{
 public static void main(String[] args){
   Otaku otaku1 = new Otaku();  //➀ Create an instance of the Otaku class! Instances are assigned to variables and used!
 //Class type variable name(Instance name) =new class name();
   Otaku otaku2 = new Otaku();
   Otaku otaku3 = new Otaku();  //➁ You can create many instances from the same class type! There are a lot of otaku!
   
   otaku1.age = "28 years old";  //➂ I will put detailed information about Otaku into each instance! This is no good human being!
   otaku1.body = "fat";  

   otaku1.usePC();  //➃ Instance name.Method name()You can use what Otaku can do!
   otaku1.specBody();  //➄ In the specBody method, "I'm fat!I want to say! Value of instance field body("fat")Want to use!
 }
}

Of this code otaku1.age = "28 years old"; otaku1.body = "Fat"; I set the value at. With this, it would be difficult if the number of instance fields increased! I don't know because there are so many!

With constructor ver

Main.java


class Main{
 public static void main(String[] args){
   Otaku otaku1 = new Otaku();  //➀ Create an instance of the Otaku class! Instances are assigned to variables and used!
 //Class type variable name(Instance name) =new class name();
   Otaku otaku2 = new Otaku();
   Otaku otaku3 = new Otaku();  //➁ You can create many instances from the same class type! There are a lot of otaku!
   
   //No!

   otaku1.usePC();  //➃ Instance name.Method name()You can use what Otaku can do!
   otaku1.specBody();  //➄ In the specBody method, "I'm fat!I want to say! Value of instance field body("fat")Want to use!
 }
}

Otaku.java


class Otaku{
 //➂ Here are the specifications of Otaku(information)I'll define! It seems that the instance field is a difficult word? But it's a variable declaration!(maybe!)
 public String age;
 public String body;

 //I'll use the constructor here! new Otaku();This method is always used when is called!
 Otaku(){
  otaku1.age = "28 years old";  //➂ I will put detailed information about Otaku into each instance! This is no good human being!
  otaku1.body = "fat"; 
 }

 //➃ What Otaku can do from here(Behavior)Is expressed by a method! Also called an instance method!
 public void usePC(){
  System.out.println("I'm a big computer teacher!");
 }
 public void specBody(){
  System.out.println("I" * this.body + "is!");  //➄ MainクラスでspecBodyメソッドが呼ばれた時に、thisをインスタンス名に置き換えるよ! これで「Iデブis!You can say!
 }
}

Rules for writing constructors!

--The constructor name should be the same as the class name --Do not write the return value (no need for void)

You can also set a value as an argument when creating an instance and pass it to the constructor!

Main.java


Otaku otaku = new Otaku("fat");

Otaku.java


class Otaku{
  public String body;
 Otaku(String body){  //"fat"Enter
  this.body = body;  //otaku.body = "fat";Same as!
 }
}

This is the case with Ruby

index.rb


class Otaku
 def initialize(name)  //What you want to do when creating an instance
  @name = name  #Instance variables(Information that the instance has(data))
 end
 def info
  puts "I#{@name}is"  #Instance variables available only within a class
 end
end

otaku = Otaku.new("fat")
otaku.info

About class fields and class methods

It's about time my head isn't catching up. Does that mean that the class can also have information?

Classes can also have methods. In the first place public static void main(String[] args){ } This is also a class method, isn't it?

Otaku.java


class Otaku{
  static int count = 0;  //Class variables(Variables that can be used in all instances)
  
  //Instance field
  public String age;
  public String body;

  //constructor
  Otaku(){
   Otaku.count++;  //Access class fields
  }
}

How to write class methods in Ruby

index.rb


class Otaku
 @@count = 0  #Definition of class variables

 def initialize(name)
  @name = name
  @@count += 1
 end
 def Otaku.data  #Class method definition self.Also possible as a class method
  puts "is name"
 end
end

Otaku.data  #Calling a class method
#Output result name

What is encapsulation ...?

No, it's tight Simply put, expose the safe parts of the features you create and limit (encapsulate) the parts you don't want to use. It can be done by restricting access to fields and methods.

Wai "I made a class! Look at this! It's amazing! I used it in other classes too!" Add "public"!

Main.java


class Main(){
 public static void main(String[] args){
  Otaku otaku = new Otaku("wai");  //Instance generation
  System.out.println(otaku.name);  //It's open to the public so you can use it!
 }
}

Otaku.java


class Otaku{
 //Instance field
 public String name;  //Add "public" so that it can be accessed from outside the class!

 //constructor
 Otaku(String name){
  this.name = name;
 }
}

Wai "I made a class! Look at this! But if I use it in another class, it seems to cause a bug, so I can't use it ..." Add "private"!

Main.java


class Main(){
 public static void main(String[] args){
  Otaku otaku = new Otaku(28);  //Instance generation
  System.out.println(otaku.age);  //error! !! !! can not use!
}

Otaku.java


class Otaku{
 //Instance field
 private int age;  //Add "private" to prevent access from the outside!

 //constructor
 Otaku(int age){
  this.age = age;  //You can use it in the same class!
 }
}

Ruby methods are public methods unless you specify anything. The method written after private becomes a private method and can only be called within the class.

However, For customers who want to get a safe value even if the instance field is private, we provide a method called "getter" that can use only the return value of the field!

Main.java


class Main{
 public static void main(String[] args){
  Otaku otaku = new Otaku("~","~","~");
  System.out.println(otaku.getName());
 }
}

Otaku.java


class Otaku{
 //Instance field
 ~
 private String name;  //This is "private", but ...
 ~

 //Instance method
 public String getName(){  //Since this is "public", it can be accessed from outside the class
  return this.name;  //Returns the value of the field
 }
}

Even in Ruby, the value of an instance variable can be obtained only within the class, so it can be obtained from outside the class using a getter.

index.rb


class Otaku
 attr_reader:name  #Getter definition
 def initialize(name)
   @name = name
 end
end

otaku = Otaku.new("Busy")
puts otaku.name

Attr_reader defines getters by doing the same thing as ↓

def name
   @name  #Return value(return omitted)
end

On the contrary, there is also a method "setter" that changes the value of the field from the outside.

Main.java


class Main{
 public static void main(String[] args){
  Otaku otaku = new Otaku("~","~","~");
  otaku.setName("washi");  //Argument set in the setName method
  System.out.println(otaku.getName());
  //Output result: washi
 }
}

Otaku.java


class Otaku{
 ~
 private String name;
 ~

 public void setName(String name){
  this.name = name;  //Set value in field
 } 
}

Setter definition in Ruby

index.rb


class Otaku
 attr_writer:name #Definition of setter
 
 def initialize(name)
  @name = name
 end
end

otaku = Otaku.new("Busy")

otaku.name = "cute"  #Call setter
puts otaku.name  #Output result is cute

Attr_writer defines a setter by doing the same thing as ↓

def name=(value)
 @name = value
end

When defining getter and setter at the same time in Ruby, you can define both at once by using "attr_accessor"

Basically,

--Field is private --Method is public

By setting it to, variables are protected privately, and methods can be used publicly in other classes, which is convenient.

Inheritance! ??

What a cool thing.

You'll want to put together code with similar content. The same is true for the content of the class. Inheriting the contents of one class by another class.

Senior "My special skill is versatile! Super usable!" (Inherited special skill (class): Super class)

Super.java


class Super{
 public void setName(String name){
  System.out.println(name);
 }
}

Junior "Senior! Let me use it!" (Special skill (class) that can be inherited: Subclass)

Sub.java


class Sub extends Super{  //Inherits the instance method of Super class
 
}

Main.java


class Main{
 public static void main(String[] args){
  Sub sub = new Sub();
  sub.setName("Hyperkinetic position reverser!!!");  //Call a superclass instance method
 }
}

In Ruby it looks like this

index.rb


class Super
 def initialize(name)
   @name = name
 end
 def info
   puts @name
 end
end

class Sub < Super
end

sub = Sub.new("Hyperkinetic position reverser!!!")  #When new is executed, the initialize method of the parent class is executed.
sub.info  #Since it inherits from the parent class, the info method can be used

If you define a method with the same name as the method inherited from the superclass in the subclass, you can overwrite the contents of the superclass. This is called "override".

Also, "private" can only be accessed from within that class, while "protected" can only be accessed from within that class and its subclasses.

What I noticed / notes

--Methods are defined in the class --this is used to point to a method or instance in a class --If you do not assign a value to the variable definition, "null" is entered for String type, "0" is entered for int type, "0.0" is entered for double type, and "false" is entered for boolean type. --Subclass instances can also call superclass methods, but not the other way around. ――The reason why I made the story of the class name a nerd is completely due to the tension at midnight. --Hyperkinetic Position Reverser is just taken from a game called LoL, so it doesn't mean anything ()

Recommended Posts

A memo for myself that object-oriented is something
A memo that touched Spring Boot
Docker execution memo summarized for myself
[MVC model] A memo that a beginner learned MVC
java.util.Arrays.asList () is not a replacement for new ArrayList <> ()
A description of Interface that is often mistaken
Awareness of object-oriented programming for half a year
[Reading Memo] Refactoring-Typecode replacement (for typecodes that affect behavior)-2
A small story that is sometimes useful in Maven
[Reading Memo] Refactoring-Typecode replacement (for typecodes that affect behavior)-1
[# 2 Java] What is object-oriented programming that you often hear?
About a double loop that puts a For statement inside a For statement
A memo that handles a class created independently with ArrayList
A memo of the program that allows you to realize that the probability of dice rolling is about 1/6
(For myself) Build an IDE that you can touch from a browser with docker (trial)