This article covers all the problems related to Java inheritance

Related articles:

  1. Object oriented re exploration : the basic concept of object-oriented is introduced
  2. Detailed explanation of object creation in Java : describes the creation of objects and the use of constructors

stay Object oriented re exploration The concept of inheritance has been introduced in general in this article. Here are the specific issues related to the use of inheritance.

1. Introduce examples

Take the Animal class and Dog class as examples. The following will focus on this example.

public class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Animal() {
    }

    public void say() {
        System.out.println("I am" + name + ",this year" + age + "Years old");
    }

    //getters and setters ...
}
public class Dog extends Animal {

    private String address;

    public Dog(String name, int age, String address) {
        super(name, age);
        this.address = address;
    }

    public Dog() {
    }

    public void say() {
        System.out.println("My name is" + super.getName() + ",this year" + super.getAge() + "Years old, live at home" + address + ",Woof, woof...");
    }

    public void watchDoor() {
        System.out.println("I am here" + address +"Janitor...");
    }

    //getters and setters ...
}

The Dog class inherits the Animal class. The Animal class has the name, age attribute and say() method. The Dog class adds the address attribute and watchDoor() method.

2. Concept introduction

In real life, there are many examples of inheritance, such as "inheriting one's father's inheritance", "inheriting one's parents' property", "inheriting one's will", etc. These are all emphasizing that one person gets something from another person, and there is an "inheritance relationship" between them.

In Java, inheritance is the relationship between classes. stay Object oriented re exploration In this article, examples of Animal animal, Dog, Cat and Rabbit are given and codes are written. They are directly used here and will not be listed. Please move to this article.

We can say that dogs, cats and rabbits are animals, but we can't say that animals are dogs, cats and rabbits. Animals generally have eyes, ears and other attributes, and have behaviors such as running, eating and barking. Dogs obviously also have these attributes and behaviors, but dogs also have some of their unique attributes and behaviors, such as sensitive nose, doorman and so on.

In this example, the Animal class is the parent class, and the Dog class, Cat class and Rabbit class are the child classes. There is an inheritance relationship between the subclass and the parent class. It can be said that the subclass is the parent class, which is an obvious feature of inheritance.

Here are some Q & as about inheritance:

Q1: when does inheritance need to be used?

A1: I think we can start from the following two points:

  1. Object-oriented language is an abstraction of the real world. The so-called "everything is an object". Then our classes in actual development must correspond to the real world, so it depends on whether there is an inheritance relationship between the real objects.
  2. When several classes have a large number of duplicate properties and methods, you can consider using inheritance to extract these duplicate properties and methods into parent classes.

Q2: how to use inheritance?

A2: the subclass inherits from the parent class by using the extends keyword. Only after using this keyword can the inheritance relationship and "parent-child class" exist:

public class Animal {//Parent class
    //Properties and methods
}
public class Dog extends Animal {//The subclass inherits the parent class
    //Properties and methods    
}

Q3: in specific development, should I write the parent class first and then extend the child class, or write the child class first and then abstract the parent class?

A3: I don't think we can generalize. If your system design is very good, you can write the parent class first, and then extend the child class. If you don't design it well or don't think it well, many classes may have duplicate code in the later stage. At this time, you can consider extracting the parent class.

Q4: what is the difference between parent and child classes in content?

A4: generally, we put some more general attributes and methods into the parent class, such as the attributes and methods of dogs, cats and rabbits. Subclasses are more special attributes and methods, such as the watchdog behavior of dogs and the mouse catching behavior of cats. Since the subclass inherits the parent class, only the differences between the subclass and the parent class need to be written.

Therefore, subclasses tend to have richer properties and methods than their parent classes.

Q5: what does the subclass inherit from the parent class?

A5: the conclusion is given here and will be introduced in detail below. Subclasses inherit the non private member variables, methods and nested classes of the parent class. Subclasses do not inherit the constructor of the parent class, but subclasses can call the constructor of the parent class.

Q6: can you inherit multiple classes in Java?

A6: inheritance in Java is single inheritance, and only one class can be inherited.

3. Specific use

3.1. Subclass overrides the method of the parent class

Sometimes the methods inherited by the subclass from the parent class are not necessarily applicable. At this time, the subclass can override the methods of the parent class. For example, the Dog class overrides the say() method of its parent class.

Pay attention to distinguish it from overloading.

In short, rewriting involves methods with the same name of two classes, and overloading involves methods with the same name of a class. For the introduction of overloading, please move to the next step here.

3.2. Add attributes and methods to subclasses

As mentioned earlier: subclass is an extension of the parent class, and the content of subclass is richer than that of the parent class. Therefore, normal subclasses will have their own properties and methods, such as the address property of Dog class and the watchDoor() method.

3.3. How do subclasses use private members of the parent class?

The subclass does not inherit the private members of the parent class, but if the parent class has public or protected methods (such as getter methods) that can access its private member variables, the subclass can use the private methods of the parent class by inheriting these methods( Official Java Tutorial).

Let's use the above code example to explain:

The Animal class has private member variables, and public methods say(). say() directly accesses the private member variables of this class, no problem!

public class Animal {
    private String name;
    private int age;
    
    public void say() {
        System.out.println("I am" + name + ",this year" + age + "Years old");
    }
    //Other codes
}

Now Dog class inherits Anima class

public class Dog extends Animal {

    private String address;
    
    public void say() {//name and age report red
        System.out.println("My name is" + name + ",this year" + age + "Years old, live at home" + address + ",Woof, woof...");
    }
    
    //Other codes
}

Please note that the say() method of the Dog class directly accesses the name and age attributes. If the subclass inherits the private members of the parent class, it is OK to write this, but the fact is that the name and age are red, indicating that the subclass does not inherit the private members of the parent class.

Although the subclass does not inherit the private member of the parent class, we can use its private member variable through the public method of the parent class. The code changes are as follows:

public class Dog extends Animal {

    private String address;
    
    public void say() {
        System.out.println("My name is" + super.getName() + ",this year" + super.getAge() + "Years old, live at home" + address + ",Woof, woof...");
    }
    
    //Other codes
}

Use super XXX () can call the method of the parent class. Because getName() is the public method of the parent class and can access the private member variable name of the parent class, the child class can use the name variable when calling getName() method.

3.4. How do subclasses assign values to private members of the parent class?

The subclass does not inherit the private member variable of the parent class. Of course, it cannot be assigned directly. There are usually two methods: calling the public setter method of the parent class or calling the constructor of the parent class. Essentially, a subclass uses its private member variables by using a public method (setter or constructor) provided by the parent class.

3.4.1. Using the setter method:

public class Dog extends Animal {

    private String address;

    public void setName(String name) {
        super.setName(name); //Attention super
    }

    public void setAge(int age) {
        super.setAge(age);
    }

    public void say() {
        System.out.println("My name is" + super.getName() + ",this year" + super.getAge() + "Live at home" + address + ",Woof, woof...");
    }

    //Other codes
}

The two setter methods of Dog class call the two setter methods of Animal class. Since the setter method name of the subclass is the same as that of the parent class (overridden), you must use the super keyword to distinguish, otherwise it will become recursion.

3.4.2. Call the constructor of the parent class:

public class Dog extends Animal {

    private String address;

    public Dog(String name, int age, String address) {
        super(name, age); //Call the parent constructor
        this.address = address;
    }

    public Dog() {
    }


    public void say() {
        System.out.println("My name is" + super.getName() + ",this year" + super.getAge() + "Years old, live at home" + address + ",Woof, woof...");
    }
    
    //Other codes
}
public class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    //Other codes
} 

The subclass uses the super() statement to call the parent class constructor, which must be the first line of code of the subclass constructor.

If the subclass constructor does not explicitly call the parent constructor, the parameterless constructor of the parent class is called by default. Therefore, if the parent class does not have a parameterless constructor and the child class does not explicitly call other constructors of the parent class, an error will be reported.

4. About me

Please correct any errors.

Tags: Java inheritance

Posted by iyia12co on Wed, 25 May 2022 02:40:07 +0300