Inheritance is a function to describe the process unique to the child class while inheriting the common process by creating a child class (subclass) based on the parent class (super class). With inheritance, you don't have to write similar programs over and over again to streamline your work and make the entire source code easier to read.
When inheriting, add "extends" after the class declaration and specify the parent class name as the inheritance source. However, there is only one class that inherits from Java. It is not possible to inherit two classes at the same time (multiple inheritance prohibited).
class class name extends the original class name{
"Difference" member with parent class
}
When using the method or constructor of the inherited class, use "super" to access and refer to it.
class class name extends the original class name(argument) {
//Call the constructor of the parent class
super(argument);
//Call the method of the parent instance part
super.Method name(argument);
}
Overriding is overriding the contents of the method defined in the parent class. It is used when you want to change the contents of the method defined in the parent class a little. The condition for overriding is that the method name, return value, and arguments are the same.
[Parent class]
public void output() {
System.out.println("Inheritance");
}
[Child class]
public void output() {
System.out.println("override");
}
It's a convenient override because you can reuse the parent class (superclass) and change the method you want to change, but there are some rules you must follow when using it. First, if a method on the parent class (superclass) side has the final modifier, the child class (subclass) cannot override that method. You should also be aware that variables and methods with the private modifier in the superclass are not available to subclasses.
Overload is a term similar to override. It's often mistaken, so I'll explain it briefly. Overloading is the declaration of multiple "methods with the same name" in a class. The condition of overload is that ➀ method names are the same ➁ argument types, numbers, and order are different.
public void output() {}
public void output(String str) {}
public void output(String str, int i) {}
public void output(int i, String str) {}
By using class inheritance, the child class does not need to rewrite the member variables and member methods of the parent class. Doing so will also make the code easier to read and will be easier to modify and maintain later.
Recommended Posts