I always read it when I explain it, so I summarize it
** Common way to send messages **
--Mechanism to share the message passed to the child class when the parent class is generated --Mechanism for sharing messages using an interface (in Java) ――One of the mechanisms to eliminate code duplication and create highly versatile parts --One of the three major object-oriented elements --Polymorphism when translated freely
** Established as a verb for each of the upper and lower concepts **
A common verb holds
--For example, "animals", "humans" and "dogs" --"Animal" (top) "eats" --"Human" (lower) "eats" --"Dog" is (lower) "eat"
I have one cut
--One option (additional information) establishes unique behavior --For example, "animals", "humans" and "dogs" ―― "Animal" "eats"-> It is not decided how to eat --"Human" (optional) of "Animal" "eats"-> Eat food by hand close to mouth --"Animal" "Dog" (optional) "Eat"-> Eat with your head close to the food
** Instances that receive arguments behave differently depending on the class **
Established with a common method name
--Established as a method for each superclass and subclass --For example, "Animal", "human", "dog" and "chef" (eater) --The "chef" provides it to the "animal" (eat-kun), and the "animal" (eat-kun) "eats" it. ――Even if you change the "animal" (Eat-kun)
Animal.java
public abstract class Animal {
public abstract void eat();
}
Human.java
public class Human extends Animal {
public void eat() {
System.out.println("Eat crunchy");
}
}
Dog.java
public class Dog extends Animal {
public void eat() {
System.out.println("Gab fluttering");
}
}
Chef.java
public class Chef {
public void serve(Animal animal) {
System.out.println("Please");
System.out.println(animal.eat());
}
}
Eater.java
public interface Eater {
public void eat();
}
Human.java
public class Human implements Eater {
public void eat() {
System.out.println("Eat crunchy");
}
}
Dog.java
public class Dog implements Eater {
public void eat() {
System.out.println("Gab fluttering");
}
}
Chef.java
public class Chef {
public void serve(Eater eater) {
System.out.println("Please");
System.out.println(eater.eat());
}
}
――The thing that can be said in common between those that use the inheritance function and those that use the interface function is that the calling method is the same regardless of the type (in this case, the person provided by the chef). --Interface is like realizing polymorphism --Some interface features are not linguistically supported (like Ruby)
Summary of why we make it object-oriented
Akira Hirasawa (Author) Why make it object-oriented, 2nd edition https://amzn.to/2VSrzwe
Even design patterns and refactoring can be applied well if you have this perspective.
Recommended Posts