Write in front: the blogger is a real combat development after training into the cause of the “hill pig”, nickname from the cartoon “Lion King” in “Peng Peng”, always optimistic, positive attitude towards things around. My technical path from Java full stack engineer all the way to big data development, data mining field, now there are small achievements, I would like to share with you what I have learned in the past, I hope to help you on the way of learning. At the same time, the blogger also wants to build a perfect technical library through this attempt. Any anomalies, errors and matters needing attention related to the technical points of the article will be listed at the end, and everyone is welcome to provide materials in various ways.

  • Please criticize any mistakes in the article and revise them in time.
  • If you have any questions you would like to discuss or learn, please contact me at [email protected].
  • The style of the published article varies from column to column, and all are self-contained. Please correct the deficiencies.

Three characteristics of Java object-oriented programming – inheritance

Keywords: Java, object-oriented, three characteristics, inheritance \

The article directories

Inheritance is one of the three characteristics of object-oriented programming. Inheritance embodies the object-oriented programming idea more incisively and vividly, allowing the correlation between classes and classes. The basic knowledge of classes and objects can enter the portal: the basic operation unit in Java – classes and objects.

First, ideological interpretation

1. What is inheritance

Starting from the concept of classes, we can define a class to describe a class of things that have the same properties and behavior. But in many cases, we hope to further refine the definition of the class, which is equivalent to a large category with many sub-categories, such as stationery can be divided into writing pens, notes, document management and so on.



If the category is more complex, it can be divided into student stationery, office stationery and accounting supplies first, and then divided under each category according to its specific function. These subcategories must have some common features or purposes of the parent category, and there may be multi-level classification relations, so if we use object-oriented language to describe such a relationship can use inheritance.



Let’s match the example to an object-oriented concept:

  • The above relationship can be described by subcategories inheriting from parent categories
  • A parent class is called a parent class or superclass
  • Subcategories are called subclasses
  • Inheritance enables a subclass to have various properties and methods of its parent class without having to write the same code again

2. What’s the use of inheritance

If we further refine the student category into: junior high school students, senior high school students and college students. Obviously, there will be some differences between classes after refinement, but there will also be common ground. If we use code to represent it, there will be many of the same attributes or methods in the three classes, with some differences:

// Define class: junior high school students
public class JuniorStudent{
    // Same attribute
    public String name;
    public int age;
    public String school;
    public String grade;
    // Other methods
}
Copy the code
// Definition class: high school students
public class SeniorStudent{
    // Same attribute
    public String name;
    public int age;
    public String school;    
    public String grade;
    // Different attributes
    public String subject;// Subject: Arts and Science
    // Other methods
}
Copy the code
// Definition category: college students
public class UniversityStudent{
    // Same attribute
    public String name;
    public int age;
    public String school;
    public String grade;
    // Different attributes
    public String college;/ / college
    public String major;/ / professional
    // Other methods
}
Copy the code

Only part of the attributes are listed above. It can be found that many attributes are completely overlapped, and the same phenomenon may exist in the methods. At this point, we can extract the same properties and methods and define a Student class, thus simplifying each class.

// Define class: students
public class Student{
    // Extract public attributes
    public String name;
    public int age;
    public String school;
    public String grade;
    // Extract the public method
}
Copy the code
// A simplified junior high school student
public class JuniorStudent extends Student{
    // Other methods
}
Copy the code
// A simplified high school student
public class SeniorStudent extends Student{
    // Different attributes
    public String subject;// Subject: Arts and Science
    // Other methods
}
Copy the code
// Simplified college students
public class UniversityStudent extends Student{
    // Different attributes
    public String college;/ / college
    public String major;/ / professional
    // Other methods
}
Copy the code
// Define the test class
public class Test{
    public static void main(String[] args){
        JuniorStudent juniorStudent = new JuniorStudent();
        juniorStudent.name = "Xiao Ming";// Normal use, from the parent class
        SeniorStudent seniorStudent = new SeniorStudent();
        seniorStudent.name = "Xiao li";// Normal use, from the parent class
        seniorStudent.subject = "Liberal arts";// Own attributes from subclasses
        UniversityStudent universityStudent = new UniversityStudent();
        universityStudent.name = "Chen";// Normal use, from the parent class
        universityStudent.college = "XX university";// Own attributes from subclasses
        universityStudent.major = "XX professional";// Own attributes from subclasses}}Copy the code

As you can see from the example above, the extends keyword is used to establish an inheritance relationship between child and parent classes. A subclass can use properties and methods defined in the parent class directly, or it can override methods in the parent class, representing its own characteristics. Using inheritance has several benefits:

  • With less code, subclasses can inherit properties and methods from their parent class
  • Improved reusability, easy maintenance
  • A subclass can express its characteristics by overwriting its parent class
  • The ability to make associations between classes is a prerequisite for polymorphism

3. Restrictions and rules on inheritance

In Java, there are some limitations to the use of inheritance, and we need to know the rules before we can better design the child and parent classes. In a word:Java does not support multiple inheritance, but does support multiple inheritance (multiple levels of inheritance), where there is only one way to find the final parent class from a subclass.

  • Single inheritance
class A{... }class B extends A{... }Copy the code
  • Multiple inheritance
class A{... }class B extends A{... }class C extends B{... }Copy the code
  • Multiple subclasses inherit from the same parent class
class A{... }class B extends A{... }class C extends A{... }Copy the code

4. How to design child and parent classes

When we need to describe a scene or realize an application system through the program, we need to build a lot of related classes, the rational use of inheritance can make the code more efficient and more conducive to maintenance. Then the construction of child and parent classes can start from the meaning represented by the class itself. If the meaning is similar or similar, and there is no major conflict between classes, then we can group them into a class. Another situation is that the original built class cannot meet the needs of the new function and needs to be improved accordingly. Then we can take the original class as the parent class and extend its subclass to make the overall function more powerful, while not having a great impact on the existing code.

  • Extract a parent class from multiple related classes

You can extract the same characteristics from AdminUser, NormalUser and VIPUser to obtain the parent class: User, which also has User name, password, nickname and other information, and also has login methods, but their implementation will be different. We can also use a mixture of inheritance methods to get the following class relationship:

  • Extending a subclass from an existing class

For a simple emporium scene, the product category design will be relatively simple, just need to identify the basic information and price. If the need to hold a second kill activity, to identify the price in the purchase page, specials, activity time and activity is introduced, and so on information, which makes that we make a class of product upgrades, if directly to modify the product class, can lead to some may not often use the attributes and methods, because of these properties and methods are purely designed for bargain. A good idea is to make the existing Product class a parent class and then extend it to a subclass, SpecialProduct, where the new information comes in.

  • A subclass is an extension or extension of a parent class, and the extends keyword is really appropriate

The use of child and parent classes

Now that you understand the concepts, let’s go back to Java syntax. The extends extends extends extends between children and parents.

// Define the parent class
public class Father{... }Copy the code
// Define subclasses that inherit from the parent class
public class Son extends Father{... }Copy the code

1. Permission modifiers

In the previous article, I introduced the use of permission modifiers, which can be accessed through portals if you don’t know: Three characteristics of Java Object-oriented programming – encapsulation. When two class hierarchy is established, although all content will be a subclass of the parent class inheritance, but because of access modifiers, without access to properties or methods will be hidden and cannot be invoked and access (when the class object instance, anti-fuzzy, superclass object will be instantiated, together will process in detail in a later article separately). In a subclass, you can call properties and methods declared by public and protected in the parent class. In a test class, you are still restricted by permission modifiers when making property calls. Here is an example:

SRC ├ ─ 07.02.txt ├ ─ 07.02.txt ├ ─ 07.02.txtCopy the code

Above is the directory structure for the entity and test classes

  • Father entity class package: edu.sandtower.bean
  • The Son entity class is a subclass of Father, under the same package as Father
  • Test Test package: edu.sandtower.test
package edu.sandtower.bean;

public class Father{
    // Private attributes in the parent class
    private double ownMoney = 2000;/ / private savings
    // Protected properties in the parent class
    protected double money = 5000;
    // Public attributes in the parent class
    public String name = "老李";
}
Copy the code
package edu.sandtower.bean;

public class Son extends Father{
    // A unique attribute in a subclass.// Test method
    public void test(a){
        Son son = new Son();
        System.out.println(son.ownMoney);// Failed to compile, unable to access private properties to view private money
        System.out.println(son.money);// The protected property is accessible in subclasses
        System.out.println(son.name);// If the compiler passes, it can access the public property}}Copy the code
package edu.sandtower.test;

import edu.sandtower.bean.Son;

public class Test{
    public static void main(String[] args){
        // Create Son instance in test class in test package
        Son son = new Son();
        son.name = "Xiao li";// Public attributes inherited from the parent class can be accessed
        // Failed to compile and cannot access the protected property in the Test class because the Test class has no parent relationship with the Father class
        son.money -= 500.0;
        // The other attributes of Son and the use of Father can be tested by ourselves}}Copy the code

As you can see from the above example, permission modifiers can be very useful. Test class for child parent class is a completely unrelated classes in different packages, in the call when it is limited by the access modifier, so here also clarify again: access modifier is according to the class path and the structure of the relationship between class defined, is not to say that in any one place using a subclass instance can call the parent class of properties and methods.

2. This and super

Knowing the rules for permission modifiers raises the question of how to assign and use attributes that cannot be accessed in other classes. In this case, you can use encapsulation, combining the use of this and super.

  • This: Refers to the current object and can call properties and methods in the current class
  • Super: Refers to a superclass object that can call properties and methods accessible in the superclass, including methods overridden by subclasses

When working with subclass instances, we can use constructors and wrapper methods if we want to use properties or methods of certain parent classes. After modifying the code, we get the following results:

package edu.sandtower.bean;

public class Father{
    // Private attributes in the parent class
    private double ownMoney = 2000;/ / private savings
    // Protected properties in the parent class
    protected double money = 5000;
    // Public attributes in the parent class
    public String name = "老李";
}
Copy the code
package edu.sandtower.bean;

public class Son extends Father{
    // A unique attribute in a subclass.// Assign values to attributes using constructors
    public Son(String name,double money){
        super.name = name;
        super.money = money;
    }
    // Use encapsulation methods to manipulate attributes in the parent class
    public void setMoney(double money){
        super.money = money;
    }
    public double getMoney(a){
        return super.money; }}Copy the code
package edu.sandtower.test;

import edu.sandtower.bean.Son;

public class Test{
    public static void main(String[] args){
        // Create Son instance in test class in test package
        Son son = new Son("Xiao li".3000);// Successfully assign attributes inherited from the parent class
        // The following code compiles
        double money = son.getMoney();
        System.out.println(money);
        son.setMoney(money - 500); }}Copy the code

3. Final modifier

Final modifiers can be used to modify properties and methods, as well as classes.

When you modify a property, if it is a primitive data type, it is considered to define a constant whose value is immutable once specified. If it is a reference type, the reference cannot be changed, that is, the value of an attribute in an array or instance can be changed, but the reference cannot be changed to point to another instance or array.



Methods modified by final cannot be overridden when inherited by subclasses,The relation of inheriting neutron parent methods will be discussed in detail in the article on polymorphism.

Classes modified by final cannot be inherited. If we think of the inheritance relationship as a tree, with the parent as the root and the subclass as the branch, then final classes must be leaves because no subclasses are guaranteed to exist.

4. Ultimate parent class: Object

When we are new to object-oriented, we may have heard of one class, Object, as if it can hold everything. All classes we define implicitly inherit from Object, that is, if our class does not have a specified parent using the extends keyword, Object is automatically considered a parent. This is done at JVM runtime, so we cannot verify this by decomcompiling. Object provides special generic methods such as toString, hashCode, equals, and so on. So why does Object hold everything? The first is because the Object class must be the ultimate parent, in other words, the root of the tree! Because if a class explicitly specifies another class as its parent, then its parent, or its parent’s parent, must implicitly inherit Object at some level. If you want to learn more about why an Object instance of any type can receive a reference to Object, check out another article: Three Features of Java Object-oriented Programming – polymorphism.

Scan the QR code below and join the official fan wechat group. You can communicate with me directly and have more benefits