There are thousands of people in the vast sea. Thank you for seeing here this second. I hope my interview question series can help you! Encourage each other!
May you keep your love and go to the mountains and seas in the future!
Java Basics (inheritance)
🍦 inherit
🍧 Introduction to inheritance
Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes. It describes the ownership relationship between things, which is the relationship of is-a.
Inheritance: a subclass inherits the properties and behaviors of the parent class, so that the subclass object (instance) can directly have the same properties and behaviors as the parent class. Subclasses can directly access non private properties and behaviors in the parent class.
🍨 Inheritance in life
Rabbits and giraffes are herbivores, tigers and lions are carnivores. Herbivores and carnivores belong to animals.
Are rabbits, giraffes, tigers and lions all animals? The answer is yes! Although herbivores and carnivores belong to animals, there are differences in their attributes and behaviors, so subclasses will have the general characteristics of their parents and their own characteristics. When the same attributes and behaviors exist in multiple classes, we can extract these contents into a single class. Then multiple classes do not need to define these attributes and behaviors, but only inherit that class.
🍩 Benefits of inheritance
- Improve code reusability (reduce code redundancy and reuse the same code).
- It creates a relationship between classes.
- Subclasses have non private properties and methods of the parent class.
- Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
- Subclasses can implement the methods of their parent classes in their own way.
- It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling will cause the closer the connection between codes, the worse the code independence).
- Java inheritance is single inheritance, but multiple inheritance is allowed. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance means, for example, class B inherits class A and class C inherits class B. therefore, according to the relationship, class B is the parent of class C and class A is the parent of class B. This is a feature of Java inheritance different from C + + inheritance.
🍪 Inherited format
In Java, the extends keyword can be used to declare that a class inherits from another class. The general form is as follows:
class Parent class { } class Subclass extends Parent class { }
One thing to note: Java does not support multiple inheritance, but supports multiple inheritance. As follows:
class A { } class B extends A { (Right) } class C extends A, B { ((wrong) } class C extends B { (Right) }
The top-level parent class is the Object class. All classes inherit Object by default as the parent class.
🎂 Inherited demo
-
Write a parent class and its corresponding subclass information
The structure is as follows:
The code is as follows:
Parent Person:
package com.nz.pojo; public class Person { private String name ; private int age ; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Subclass Student has no additional properties and methods:
package com.nz.pojo; /** * Inherits the unique name and age of Person, * There are no additional unique properties and methods */ public class Student extends Person{ }
The subclass Teacher has a salary attribute and a unique teaching method:
package com.nz.pojo; /** * Inherits the unique name and age of Person, * With their own unique salary attributes and unique teaching methods */ public class Teacher extends Person{ // wages private double salary ; // Unique method public void teach(){ System.out.println("The teacher is teaching seriously!"); } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } }
-
Write test code:
package com.nz; import com.nz.pojo.Student; import com.nz.pojo.Teacher; public class InheritDemo { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("Prince Nezha"); teacher.setAge(18); teacher.setSalary(1999.99); System.out.println(teacher.getName()); System.out.println(teacher.getAge()); System.out.println(teacher.getSalary()); teacher.teach(); Student student = new Student(); student.setName("nezha"); student.setAge(12); //student.setSalary(1999.99); // student does not have salary attribute, error is reported! System.out.println(student.getName()); System.out.println(student.getAge()); } }
The results are as follows:
Prince Nezha 18 1999.99 The teacher is teaching seriously! nezha 12
From the result, if the subclass inherits the parent class, you can directly get the member variables and methods of the parent class. Subclasses can write some unique properties and methods, but can they inherit all components?
🍬 Content that subclasses cannot inherit
Not all contents of the parent class can be inherited by the child class:
🍭 super and this keywords
Here, the two keywords, super and this, are used frequently in the inheritance relationship.
-
Super keyword: we can access the members of the parent class through the super keyword, which is used to reference the parent class of the current object.
-
this keyword: a reference to your own class.
The complete usage of super and this is as follows:
this.Member variable -- Of this class super.Member variable -- Parent class this.Member's legal name() -- Of this class super.Member's legal name() -- Parent class
-
For specific demonstration, create test InheritDemo2:
package com.nz; public class InheritDemo2 { public static void main(String[] args) { Animal a = new Animal(); a.eat(); Cat cat = new Cat(); cat.eatFish(); } } class Animal { void eat() { System.out.println("animal : eat"); } } class Cat extends Animal { void eat() { System.out.println("cat : eat"); } void eatFish() { this.eat(); // this calls its own method super.eat(); // super calls the parent class method } }
The call result is as follows:
animal : eat cat : eat animal : eat
-
be careful:
Each construction method of a subclass has a default super(), which calls the null parameter construction of the parent class. Manually calling the parent class construct overrides the default super().
Both super() and this() must be in the first line of the constructor, so they cannot appear at the same time.
🍮 Constructors cannot be inherited
-
A subclass cannot inherit the constructor (constructor or constructor) of the parent class. It is just a call (implicit or explicit). Because subclasses have their own constructors. It is worth noting that subclasses can inherit the private members (member variables and methods) of the parent class, but subclasses cannot access them directly. You can access the private member variables of the parent class through getter/setter methods.
-
If the constructor of the parent class has parameters, the constructor of the parent class must be explicitly called through the super keyword in the constructor of the child class with the appropriate parameter list.
-
If the parent constructor has no parameters, it is not necessary to use the super keyword to call the parent constructor in the constructor of the child class, and the system will automatically call the parameterless constructor of the parent class.
-
Demonstration process:
package com.nz; public class InheritDemo3 { public static void main(String[] args) { System.out.println("------Teacher Class inheritance------"); Teacher teacher = new Teacher(); Teacher teacher2 = new Teacher("Zhang San"); System.out.println("------Student Class inheritance------"); Student student = new Student(); Student student2 = new Student("Zhang Sansan"); } } // Parent class class Person { private String name; Person(){ System.out.println("The parameterless constructor of the parent class was called: Person()"); } Person(String name) { System.out.println("The parameterized constructor of the parent class was called: Person(String name)"); this.name = name; } } // Teacher subclass inherits Person class Teacher extends Person{ private String name; Teacher(){ // Automatically call the parameterless constructor of the parent class because there will be a default super(); System.out.println("Teacher"); } public Teacher(String name){ super("Prince Nezha"); // Call the constructor with parameters in the parent class System.out.println("Teacher(String name):"+name); this.name = name; } } // Student subclass inherits Person class Student extends Person{ private String name; Student(){ super("heihei"); // Call the constructor with parameters in the parent class System.out.println("SubClass2"); } public Student(String name){ // Automatically call the parameterless constructor of the parent class System.out.println("Student(String name):"+name); this.name = name; } }
The results are as follows:
------Teacher Class inheritance------ The parameterless constructor of the parent class was called: Person() Teacher The parameterized constructor of the parent class was called: Person(String name) Teacher(String name):Zhang San ------Student Class inheritance------ The parameterized constructor of the parent class was called: Person(String name) SubClass2 The parameterless constructor of the parent class was called: Person() Student(String name):Zhang Sansan
🍯 final decorated classes cannot be inherited
The final keyword is mainly used in three places: variables, methods, and classes.
- Decorated class: indicates that this class cannot be inherited;
- Modifier method: indicates that the method cannot be overridden;
- Modified variable: indicates that the variable can only be assigned once, and the value cannot be modified (constant).
Features of final:
- For a final variable, if it is a variable of basic data type, its value cannot be changed after initialization; If it is a variable of reference type, it can no longer point to another object after its initialization.
- When a class is modified with final, it indicates that the class cannot be inherited. All member methods in the final class are implicitly specified as final methods.
- There are two reasons for using the final method. The first reason is to lock the method to prevent any inherited class from modifying its meaning; The second reason is efficiency. In earlier Java implementations, the final method was turned into an inline call. However, if the method is too large, you may not see any performance improvement brought by embedded calls (the current java version does not need to use the final method for these optimizations). All private methods in the class are implicitly specified as final.
Let's test whether the modified class can inherit or not:
package com.nz; public class InheritDemo4 { } // Parent class final class Fu { private String name; } //Class Zi extends fu{/ / cannot inherit from final 'com. NZ. Fu' displays that you cannot inherit Fu //}
Results: it can be seen that the Fu class modified by final cannot inherit, and an error will be reported during compilation, so it cannot be run.
🍼 Method rewrite
🧅 introduce
Subclass appears as like as two peas in the same way as the parent class (the return value type, the method name and the parameter list are the same), and the overlay effect appears, also known as rewriting or copying. The declaration remains unchanged and re implemented.
🍄 Usage scenarios and cases
Relationships that occur between child and parent classes.
The subclass inherits the method of the parent class, but the subclass feels that the method of the parent class is not enough to meet its own needs. The subclass rewrites a method with the same name as the parent class to override the method of the parent class.
Write a test case:
package com.nz; public class InheritDemo5 { public static void main(String[] args) { // Create subclass objects Cat lanMao = new Cat(); // Call the method inherited from the parent class lanMao.run(); // Call the method overridden by the subclass lanMao.sing(); } } class Animal{ public void sing(){ System.out.println("Animals can sing!"); } public void run(){ System.out.println("Animals can run!"); } } class Cat extends Animal { public void sing(){ System.out.println("Let's learn to bark and meow together! Let's do it together"); } }
Operation results:
Animals can run! Let's learn to bark and meow together! Let's do it together
It can be seen that the blue cat called the rewritten sing method.
🥜 @ Override override annotation
-
@Override: annotation, override annotation verification!
-
The method marked by this annotation indicates that this method must be a method that overrides the parent class, otherwise an error will be reported at the compilation stage.
-
It is recommended to add this annotation for rewriting. On the one hand, it can improve the readability of the code and prevent rewriting errors on the other hand!
The subclass code after addition is as follows:
class Cat extends Animal { // Declaration unchanged, re implementation // The method name is the same as that of the parent class, except that the function in the method body has been overridden! @Override public void sing(){ System.out.println("Let's learn to bark and meow together! Let's do it together"); } }
🌰 matters needing attention
- Method overrides are relationships that occur between child and parent classes.
- If the subclass method overrides the parent method, the permission must be greater than or equal to the parent permission.
- As like as two peas, the subclass method covers the parent class method, and the return value, function name and parameter list are exactly the same.
🌸 end
I believe all of you have a certain understanding of Java inheritance. Inheritance still plays a much larger role in Java features. It also has many features:
-
High code reusability (reduce code redundancy and reuse the same code).
-
It creates a relationship between classes.
-
Subclasses have non private properties and methods of the parent class.
-
Subclasses can have their own properties and methods, that is, subclasses can extend the parent class and implement the methods of the parent class in their own way.
-
It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling will cause the closer the connection between codes, the worse the code independence).
Let's cheer together! I am not talented. If there are any omissions and mistakes, I also welcome criticism and correction in the comments of talent leaders! Of course, if this article is sure to be of little help to you, please also give some praise and collection to the kind and lovely talent leaders. Thank you very much!
Learn here, today's world is closed, good night! Although this article is over, I am still there and will never end. I will try to keep writing articles. The future is long. Why are you afraid of cars and horses!
Thank you for seeing here! May you live up to your youth and have no regrets!