The next two days will introduce a very core concept of object-oriented programming: Inheritance
Inheritance is a method used in classes that simply means to add code while retaining the original content.
Since we mentioned “inheritance”, we can also cite the data structure that is also a very well-known concept: the binary tree (B tree).
Binary trees themselves use the concept of inheritance, with child nodes inheriting from their parent nodes, and object-oriented programming also uses a similar concept.
As we mentioned earlier, in Java, there is “unidirectional inheritance”:
a parent class can be inherited by multiple child classes; however, a child class cannot inherit 2 or more parent classes at the same time.
To sum up:
The keyword extends
is used to declare that one class inherits from another.
class School{
/*...........
description
...........*/
}
class Student extends School{
/*......................
description in School
......................*/
/*............
description
............*/
}
The child class (Student) inherits the content of the parent class (School) and adds a new program.
-> The last instruction for class inheritance is extends + parent class name.
These cannot be directly inherited by the child class. Private variables, for example, need to be accessed using the get
and set
concepts within the package.
Here we introduce the previously mentioned prefix modifier protected
that can be inherited by the quilt category
class School{
protected String name = "Chi";
protected float warning;
public void show_Sname(){
System.out.println("Personal Information : " + name);
}
}
class Student extends School{
public void show_warning(int late){
warning = late / 3;
System.out.println("You hava " + warning + " warnings");
}
}
public class Main{
public static void main(String[] args){
Student paper = new Student();
int late = 21;
paper.show_Sname();
paper.show_warning(late);
}
}
protected
. Its access permissions can be granted to subclasses and classes in the same package. Assuming that this is changed to the default mode, it cannot be inherited by subclasses.This chapter focuses on what inheritance is and how to use it. The next chapter is also about inheritance, but it will introduce more advanced topics such as how private is inherited and explain different inheritance concepts using object-related keywords.