[Javase Study Notes]-9.1 inheritance
In this section, we learn the second feature of the object-oriented model-inheritance.
So what is inheritance? What is the role of inheritance?
Here is an example:
Class Student // Student class {String name; // name int age; // age void printInfo () // print information {System. out. println ("name:" + name + "\ t age:" + age);} void study () // students are learning {System. out. println (name + "is learning. ") ;}} Class Worker // Worker {String name; // name int age; // age void printInfo () // print information {System. out. println ("name:" + name + "\ t age:" + age);} void work () // work in {System. out. println (name + "is working. ") ;}} Class ExtendTest {public static void main (String [] args) {Student student = new Student (); student. name = "Xiaoqiang"; student. age = 15; student. printInfo (); student. study (); Worker worker = new Worker (); worker. name = "bald head"; worker. age = 28; worker. printInfo (); worker. work ();}}The result is as follows:
Here we have defined two classes: one is a student class and the other is a human worker, but we will find that the above Code already contains too much content, which is contrary to the code reuse we want to implement, so we can see that for students and jobs, what they share is that they are all one Person and all the features of others, so here we can redefine a Person class, as shown below:
Class Person {String name; int age; void printInfo () {System. out. println ("name:" + name + "\ t age:" + age );}}In the Person class, we encapsulate the common characteristics, names and ages of people, and a method for printing information.
So what should we do? Of course, it is necessary to establish the relationship between the Student class and the Worker class and the Person class. This is the inheritance we will talk about in this section, so that both the Student class and the Worker class will inherit from the Person class, you can directly inherit these total members.
We can use the extends keyword to implement inheritance:
Class Student extends Person // Student class {void study () // the Student is learning {System. out. println (name +. ") ;}} Class Worker extends Person // Worker {void work () // work in {System. out. println (name +" working. ");}}Result:
At this time, we will find that the running results are normal and we want to see them. However, compared with the previous code, we actually improved the reusability of the Code.
We can also summarize the advantages of inheritance:
1. Improved code reusability.
2. The relationship between classes provides a prerequisite for the third object-oriented feature "polymorphism.