I will post it as a review of ** Abstraction ** and ** Interface **.
In the upper module, declare the methods and variables that are commonly implemented in the lower module, and leave the implementation to the lower module. Also, abstracted classes cannot be instantiated.
**-Advantages of abstraction ** --Prevention of forgetting to override —— Make a distinction from processing that does nothing --Prevention of unintended instantiation
Human.java
public abstract class Human{
private String name;
public Human(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
//Declare common methods and leave implementation to lower modules
public abstract void talk();
//Method that does nothing
public void tmp(){}
}
Japanese.java
public class Japanese extends Human{
public Japanese(String name){
super(name);
}
@Override
public void talk(){
System.out.println("Hello");
}
}
American.java
public class American extends Human{
public American(String name){
super(name);
}
@Override
public void talk(){
System.out.println("Hello");
}
}
Main.java
public class Main{
public static void main(String[] args){
//Human human = new Human("Yamada Taro");
//Compile error because instance cannot be created
Japanese jp = new Japanese("Yamada Taro");
jp.talk(); //Hello
American en = new American("TaroYamada");
en.talk(); //Hello
}
}
In the interface, you can declare a method to be implemented in common as in the abstraction, and leave the implementation to the class that inherits the interface. However, fields are treated differently from abstract classes.
** Interface features ** --Basically, it doesn't have any fields --All methods are abstract methods.
Basically, it is not allowed to implement fields in the interface, but only fields with ** public static final ** can be declared, and they are automatically added when the variable declaration is started from the type name in the interface. Will be done. Since it has a ** final ** modifier that cannot be reassigned, it must be initialized at the same time as the variable declaration.
Regarding methods, the methods that can be declared in the interface are limited to those that are ** public ** and ** abstract **, and are automatically added when declared from the return type.
Creature.java
public interface Creature{
//public static final double PI = 3.14;
double PI = 3.14; //It automatically becomes a public static final variable.
//public abstract void breath();
void breath(); //It automatically becomes a public abstract method.
}
My honest impression is that it is difficult to benefit from the benefits because I have little development experience using inheritance.
Recommended Posts