Java - Inheritance and Composition

Table of contents

1. Why inheritance is needed

2. Inheritance concept

3. Inheritance Syntax

4. Parent class member access

5. super keyword

6. Subclass construction method

7. super and this

8. Look at initialization again

9. protected keyword

10. Inheritance method

11. final keyword

12. Inheritance and Composition


1. Why inheritance is needed

             Classes are used in Java to describe entities in the real world, and the product objects after class instantiation can be used to represent real entities, but the real world is intricate, and there may be some associations between things. Example: Animals dogs and cats.
        

         To describe them, you can have the following code

public class Dogs {//dog
    String name;
    int age;
    float weight;
    public void eat(){
        System.out.println(this.name+"is eating");
    }
    public  void sleep(){
        System.out.println(this.name+"Sleeping");
    }
    public void bark(){
        System.out.println(this.name+"Wow~~~");
    }
}
public class Cats {//猫
    String name;
    int age;
    float weight;
    public void eat(){
        System.out.println(this.name+"is eating");
    }
    public  void sleep(){
        System.out.println(this.name+"Sleeping");
    }
    public void mew(){
        System.out.println(this.name+"喵喵喵~~~");
    }
}

        

                 For the code blocks they have in common, can we extract these commonalities? The concept of inheritance is proposed in object-oriented thinking, which is specially used for commonality extraction and code reuse.

2. Inheritance concept

        Inheritance (inheritance) mechanism : It is the most important means for object-oriented programming to make code reusable . It allows programmers to expand and add new functions on the basis of maintaining the characteristics of the original class, thus generating new classes, called derivation class . Inheritance presents the hierarchical structure of object-oriented programming , reflecting the cognitive process from simple to complex. The main problem solved by inheritance is: the extraction of commonality and the realization of code reuse .

           Like the cats and dogs above, we can extract their commonality and realize it with the idea of ​​inheritance.

          In the above diagram, both Dog and Cat inherit the Animal class, among which: the Animal class is called the parent class/base class or super class, and Dog and Cat can be called the subclass/derived class of Animal. After inheritance, the subclass can be repeated Use the members in the parent class, and the subclass only needs to care about its newly added members when implementing. The biggest role of inheritance is to realize code reuse and polymorphism.
 

3. Inheritance Syntax

             In Java, if you want to express the inheritance relationship between classes, you need to use the extends keyword.

        Modifier class subclass extends parent class{

                //....

        }

          Use inheritance for the above code.

public class Animals {
    String name;
    int age;
    float weight;
    public void eat(){
        System.out.println(this.name+"is eating");
    }
    public  void sleep(){
        System.out.println(this.name+"Sleeping");
    }
}
public class  Dogs extends Animals{
     public  void bark(){
        System.out.println(this.name+"Wow~~~");
    }
}
public class Cats extends Animals{
    public void mew(){
        System.out.println(this.name+"喵喵喵~~~");
    }
}
public class TextJicheng {
    public static void main(String[] args) {
        Dogs dog=new Dogs();
        //There is no member variable in Dogs, inherit from the parent class
        System.out.println(dog.name);
        System.out.println(dog.age);
        //There are no eat and sleep functions in Dogs, inherit from the parent class
        dog.eat();
        dog.sleep();
        dog.bark();
    }
}

                 Note: The subclass will inherit the member variables or member methods in the parent class to the subclass ; after the subclass inherits the parent class, it must add its own unique members to reflect the difference from the base class, otherwise there is no need to inherit .

4. Parent class member access

                In the inheritance system, the subclass inherits the methods and member variables of the parent class, so can the subclass directly access the inherited members of the parent class?

      1. Access the member variables of the parent class in the subclass

           (1) There is no member variable with the same name in the subclass and the parent class

public class  Dogs extends Animals{
     public  void bark(){
        System.out.println(this.name+"Wow~~~");
    }
    public void mathod(){
         name="huahua";
         age=5;
         weight=5.2f;
    }
}

       (2) Subclass and parent class member variables have the same name

public class Cats extends Animals{
    String name;
    String color;
    public void mew(){
        System.out.println(this.name+"喵喵喵~~~");
    }
    public void mathod(){
        name="Saihu";//same name
        age=4; //There is in the parent class
        color="black and white";//There is no parent class
    }
}

          When accessing members in subclass methods or through subclass objects :

  • If the member variable to be accessed exists in the subclass, access to its own member variable is given priority.
  •  If the accessed member variable does not exist in the subclass, it will access the one inherited from the parent class. If the parent class is not defined, the compiler will report an error.
  •  If the member variable to be accessed has the same name as the member variable in the parent class , it will be accessed first.

      2. Access the member method of the parent class in the subclass
             (1) The name of the member method is different  

public class  Dogs extends Animals{
     public  void bark(){
        System.out.println(this.name+"Wow~~~");
    }
    public void method(){
         bark(); // access to subclass method
         eat(); //Access the method of the parent class
    }
     
    public static void main(String[] args) {
     Dogs dog=new Dogs();
     dog.method();
    }
}

         Summary: When the member methods have different names , in the subclass method or when accessing the method through the subclass object, you will first access your own method, and if you don’t have it, then go to the parent class to find it. If there is no parent class, you will report an error .

                (2) Member method names are the same

public class Cats extends Animals{
    String name;
    String color;
    public void mew(){
        System.out.println(this.name+"喵喵喵~~~");
    }
    
    public void sleep(){
        System.out.println(this.name+"waking up");
    }
    public static void main(String[] args) {
        Cats cat=new Cats();
        cat.sleep();
    }
}

         Summarize:

  • When accessing a method with a different name in the parent class and the subclass through the subclass object , first look for it in the subclass, and access it if you find it, otherwise look for it in the parent class, and access it if you find it, otherwise, compile and report an error.
  • When accessing the method with the same name of the parent class and the subclass through the subclass object , if the parameter list of the method with the same name of the parent class and the subclass is different (overloading), select the appropriate method access according to the parameters passed by the calling method, and report an error if there is no .

If the subclass has the same member as the parent class, how to access the member with the same name as the parent class in the subclass?

5. super keyword

        Due to poor design or due to the needs of the scenario, there may be members with the same name in the subclass and the parent class. What should I do if I want to access the members of the parent class with the same name in the method of the subclass ? Direct access is impossible. Java provides the super keyword . The main function of this keyword is to access the members of the parent class in the subclass method .

public class Animals {
    String name;
    int age;
    float weight;

    public void eat(){
        System.out.println(this.name+"is eating");
    }
    public  void sleep(){
        System.out.println(this.name+"Sleeping");
    }
    
}
public class Cats extends Animals{
    String name;
    String color;
    public void mew(){
        System.out.println(this.name+"喵喵喵~~~");
    }
    public void mathod(){
        name="Saihu";//Member variable with the same name, access subclass
        age=4; //same name, access subclass
        color="black and white";//There is no parent class
        
        super.name="feifei";//Access parent class member variables
        super.age=3;

        sleep();//method overloading
        sleeo(5);
        System.out.println("=====");
        eat();
        super.eat();//Access the method with the same name in the parent class through super
    }
        //Method overloading, distinguish the parameter list to access the method
    public void sleep(int a){
        System.out.println(this.name+"waking up");
    }
    
        //Constitute rewriting with eat() of the parent class
     public  void eat(){
         System.out.println(this.name+"Don't eat");
     }
    public static void main(String[] args) {
        Cats cat=new Cats();
        cat.method();
    }
}

 

         In the subclass method, if you want to access the member variable with the same name in the parent class or constitute rewriting with the subclass method, you need to use the super keyword, and super can only be used in non-static methods .

6. Subclass construction method

        Father and son, father and son, there is a father first and then a child, that is, when constructing a subclass object, you need to call the parent class construction method first, and then execute the subclass construction method.

public class Animals {
    String name;
    int age;
    float weight;
    public void eat(){
        System.out.println(this.name+"is eating");
    }
    public  void sleep(){
        System.out.println(this.name+"Sleeping");
    }
    public Animals(){ //Construction method
        System.out.println("Animals()");
    }
}
public class  Dogs extends Animals{
     public  void bark(){
        System.out.println(this.name+"Wow~~~");
    }
    public void mathod(){
         name="huahua";
         age=5;
         weight=5.2f;
    }
    public void method(){
         bark(); // access to subclass method
         eat(); //Access the method of the parent class
    }
    public Dogs(){ //construction method
        System.out.println("Dogs()");
    }

    public static void main(String[] args) {
         Dogs dog=new Dogs();
    }
}

         In the subclass construction method, no code about the construction of the parent class is written, but when constructing the subclass object, the construction method of the parent class is executed first, and then the construction method of the subclass is executed, because: the members of the subclass object are It consists of two parts, inherited from the parent class and newly added by the subclass. Father and son must have father first and then son, so when constructing a subclass object, first call the construction method of the parent class to complete the construction of the members inherited from the parent class, and then call the construction method of the subclass itself, which will The newly added members of the subclass are fully initialized.

       Notice:

        1. If the parent class explicitly defines a no-argument or default construction method, there is an implicit super() call by default in the first line of the subclass construction method, that is, the base class construction method is called.

        2. If the parent class construction method has parameters, the user needs to explicitly define the construction method for the subclass, and select the appropriate parent class construction method call in the subclass construction method, otherwise the compilation will fail.

        3. In the subclass constructor, when super(...) calls the superclass constructor, it must be the first statement in the subclass constructor.

        4. super(...) can only appear once in the subclass constructor, and cannot appear at the same time as this .

7. super and this

        Both super and this can be used in member methods: member variables and calling other member functions can be used as the first statement of the construction method, so what is the difference between them? The same point: they are all keywords
        in Java ; they can only be used in non-static methods of a class to access non-static member methods and fields ; when called in a construction method, it must be the first statement in the construction method, and cannot exist at the same time .

        Differences: this is the reference of the current object , the current object is the object calling the instance method, super is equivalent to the reference of some members inherited from the parent class in the subclass object ; in the non-static member method, this is used to access this class Methods and properties , super is used to access the methods and properties inherited from the parent class ; in the construction method: this(...) is used to call the construction method of this class , super(...) is used to call the construction method of the parent class , The two calls cannot appear in the construction method at the same time ; there must be a super(...) call in the construction method, and the compiler will increase if the user does not write it, but this(...) will not exist if the user does not write it .

8. Look at initialization again

        Remember the code block we talked about earlier? Briefly review several important code blocks: instance code block and static code block. Execution order when there is no inheritance relationship.

class Persons {
    public String name;
    public int age;
    public Persons(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("construct method execution");
    }
    {
        System.out.println("Instance code block execution");
    }
    static {
        System.out.println("Static code block execution");
    }
}
public class Person {
        public static void main(String[] args) {
            Persons person1 = new Persons("zhangsan",10);
            System.out.println("=======");
            Persons person2 = new Persons("lisi",15);
        }
}

 

         Execution sequence: Execute the static code block (executed only once, in the class loading phase) ---> execute the instance code block (with object creation) ---> the construction method.

        Execution order on inheritance relationship

class Persons {
    public String name;
    public int age;
    public Persons(String name, int age) {
        this.name = name;
        this.age = age;
        System.out.println("Execute the constructor");
    }
    {
        System.out.println("execute example code block");
    }
    static {
        System.out.println("Execute static code block");
    }
}
class Student extends Persons{
        public Student(String name,int age){
            super(name,age);
            System.out.println("Execute the constructor");
        }
    {
        System.out.println("execute example code block");
    }
    static {
        System.out.println("Execute static code block");
    }
}
public class Person {
        public static void main(String[] args) {
           Student person1 = new Student("zhangsan",10);
            System.out.println("=======");
            Student person2 = new Student("lisi",15);
        }
}

 

 

         Execution order: parent class static code block--->subclass static code block--->parent class instance code block--->parent class construction method--->subclass instance code block--->subclass construction method.

9. protected keyword

        In the class and object chapter, in order to realize the encapsulation feature, Java introduces access qualifiers, which mainly limit whether a class or members of a class can be accessed outside the class or in other packages.

 What is the visibility of members with different access permissions in the parent class in the subclass?

        //package 1

public class B {
    private int a;
    protected int b;
    public int c;
    int d;
}

        // subclasses in package 1

public class D extends B{
    public void method(){
        //super.a=10; //Compilation error, private members in parent class B are not visible in the same package subclass
        super.b=20; //The protected members in the parent class B can be accessed in the same package subclass
        super.c=10; //public members in parent class B can be accessed in the same package subclass
        super.d=2; //The defult members in the parent class B can be accessed in the same package subclass
    }
}

        // subclass in package 2

public class C extends B {
    public void  method(){
        //super.a; //Compilation error, the private modified members in the parent class B are not visible in different package subclasses
        super.b=10; //The protected modified members of the parent class are visible in different packages
        super.c=50; //The public modified members of the parent class are visible in different packages
        //super.d=100; //Compilation error, the members modified by the parent class defult are not visible in different packages
    }
}

        //Other classes in package 2

public class TextC {
   public static void main(String[] args) {
       C c=new C();
       c.method();
    //System.out.println(ca);//Compilation error reports that the private modified members in the parent class are not visible in other classes in different packages
   //System.out.println(cb);//compilation error reports that the protected modified members of the parent class are not visible in other classes in different packages
      System.out.println(cc);//The public modified members in the parent class can be accessed in other classes in different packages
    //System.out.println(cd);// compile error, the members modified by defult in the parent class are not visible in other classes in different packages
    }
}

        Note: Although the private modified member variables in the parent class cannot be directly accessed in the subclass, they are also inherited to the subclass.
        When to use which one?

        We hope that the class should be "encapsulated" as much as possible, that is, to hide the internal implementation details and only expose the necessary information to the caller of the class . Therefore, we should use stricter access permissions as much as possible when using it . For example, if a method If you can use private, try not to use public .
 

10. Inheritance method

        In real life, the relationship between things is very complex, flexible and diverse, such as:
 

         However, the following inheritance methods are supported in Java:

         We don't want the inheritance levels between classes to be too complicated. Generally, we don't want more than three levels of inheritance . If there are too many levels of inheritance, we need to consider refactoring the code. If you want to restrict inheritance syntactically, you can use the final keyword.

11. final keyword

        The final key can be used to modify variables, member methods, and classes.

        (1) Modify variables or fields to represent constants (that is, cannot be modified)

                final int a = 10;
                a = 20; // compile error

        (2) Modified class: Indicates that this class cannot be inherited

                final public class Animal {                         ...                 }                 public class Bird extends Animal {                         ...                 } // compile error, A can no longer be inherited




            (3) Modification method: Indicates that the method cannot be overridden (introduction later)
 

12. Inheritance and Composition

        Similar to inheritance, composition is also a way to express the relationship between classes , and it can also achieve the effect of code reuse . Composition involves no special syntax (keywords such as extends ), just an instance of one class as a field of another class . Inheritance means that there is an is-a relationship between objects , such as: a dog is an animal, and a cat is an animal. Composition means that there is a has-a relationship between objects , such as: a car.

Car Structural Diagram_Bora Forum_Pacific Automotive Network Forum
        The relationship between a car and its tires, engine, steering wheel, on-board system, etc. should be a combination, because a car is composed of these parts. 

// Tire
class class Tire{         // ... }

// engine class
class Engine{         // ... }

// vehicle system
class class VehicleSystem{         // ... } class Car{


        private Tire tire; // properties and methods in the tire can be reused
        private Engine engine; // properties and methods in the engine can be reused
        private VehicleSystem vs; // properties and methods in the vehicle system can be reused

        //...

}

//Mercedes-Benz is a car
class Benz extend Car{         // Inherit everything contained in the car: tires, transmitters, and on-board systems }

         Both composition and inheritance can achieve code reuse. Whether inheritance or composition should be used depends on the application scenario. It is generally recommended to use composition as much as possible .

        

Guess you like

Origin blog.csdn.net/qq_64668629/article/details/132041475