Object-Oriented Programming (Advanced) 2: Object-Oriented Feature 2: Inheritance

Table of contents

2.1 Overview of inheritance

2.1.1 Inheritance in life

Property Inheritance:

Greening: predecessors plant trees, descendants enjoy the shade

Appearance:

2.1.2 Inheritance in Java

Angle 1: from top to bottom

Angle 2: Bottom-up

​edit

Another example:

2.1.3 Benefits of inheritance

2.2 Syntax of Inheritance

2.2.1 Grammatical format in inheritance

2.2.2 Basic concepts in inheritance

2.3 Code example

1. Parent class

2. Subclasses

3. Test class

2.4 Details of Inheritance

1. The subclass will inherit all the instance variables and instance methods of the parent class

2. Subclasses cannot directly access private member variables and methods in the parent class

3. In Java, the keyword of inheritance is "extends", that is, the subclass is not a subset of the parent class, but an "extension" of the parent class

4. Java supports multi-layer inheritance (inheritance system)

5. A parent class can have multiple subclasses at the same time

6. Java only supports single inheritance, not multiple inheritance

2.5 Exercises

**Exercise 1:**

Exercise 2:


2.1 Overview of inheritance

2.1.1 Inheritance in life

  • Property Inheritance:

  • Greening: predecessors plant trees, descendants enjoy the shade

"Green water and green mountains are mountains of gold and silver"

  • Appearance:

  • In addition to inheritance, is it possible to " 进化":

Inheritance has the meaning of continuation (the next generation continues the genes and wealth of the previous generation) and expansion (the next generation is different from the previous generation).

2.1.2 Inheritance in Java

Angle 1: from top to bottom

To describe and process personal information, define the class Person:

To describe and process student information, define class Student:

Simplify the definition of the Student class by inheritance:

Description: The Student class inherits all the properties and methods of the parent class Person, and adds an attribute school. The attributes and methods in Person can be used by Student.

Angle 2: Bottom-up

When the same attributes and behaviors exist in multiple classes, extract these contents into a single class, then there is no need to define these attributes and behaviors in multiple classes, and only need to be composed with the extracted classes

Another example:

2.1.3 Benefits of inheritance

  • The emergence of inheritance reduces code redundancy and improves code reusability.

  • The emergence of inheritance is more conducive to the expansion of functions.

  • The emergence of inheritance creates is-aa relationship between classes and classes, which provides a prerequisite for the use of polymorphism.

    • Inheritance describes the ownership relationship between things, this relationship is: is-a the relationship. It can be seen that the parent class is more general and general, and the subclass is more specific.

Note: Don't inherit just to get a function in another class!

2.2 Syntax of Inheritance

2.2.1 Grammatical format in inheritance

Through  extends keywords, you can declare that a class B inherits another class A, and the definition format is as follows:

[修饰符] class 类A {
	...
}

[修饰符] class 类B extends 类A {
	...
}

2.2.2 Basic concepts in inheritance

Class B, called subclass, derived class (derived class), SubClass

Class A, called parent class, super class, base class (base class), SuperClass

2.3 Code example

1. Parent class

package com.atguigu.inherited.grammar;

/*
 * 定义动物类Animal,做为父类
 */
public class Animal {
    // 定义name属性
    String name;
    // 定义age属性
    int age;

    // 定义动物的吃东西方法
    public void eat() {
        System.out.println(age + "岁的"
                + name + "在吃东西");
    }
}

2. Subclasses

package com.atguigu.inherited.grammar;

/*
 * 定义猫类Cat 继承 动物类Animal
 */
public class Cat extends Animal {
    int count;//记录每只猫抓的老鼠数量

    // 定义一个猫抓老鼠的方法catchMouse
    public void catchMouse() {
        count++;
        System.out.println("抓老鼠,已经抓了"
                + count + "只老鼠");
    }
}

3. Test class

package com.atguigu.inherited.grammar;

public class TestCat {
    public static void main(String[] args) {
        // 创建一个猫类对象
        Cat cat = new Cat();
        // 为该猫类对象的name属性进行赋值
        cat.name = "Tom";
        // 为该猫类对象的age属性进行赋值
        cat.age = 2;
        // 调用该猫继承来的eat()方法
        cat.eat();
        // 调用该猫的catchMouse()方法
        cat.catchMouse();
        cat.catchMouse();
        cat.catchMouse();
    }
}

2.4 Details of Inheritance

1. The subclass will inherit all the instance variables and instance methods of the parent class

From the definition of a class, a class is an abstract description of a class of things with the same characteristics. A superclass is an abstract description of the common characteristics of all subclasses. Instance variables and instance methods are the characteristics of things, so the instance variables and instance methods declared in the parent class represent the characteristics of subclass things.

  • When a subclass object is created, when applying for memory for the object in the heap, it depends on what instance variables are declared by both the subclass and the parent class, and these instance variables must allocate memory.
  • When a subclass object calls a method, the compiler will first check whether the class has this method in the subclass template. If it does not find it, it will check whether its parent class or even the parent class of the parent class declares this method 从下往上. order, stop when it is found, until the root parent class is not found, a compilation error will be reported.

So inheritance means that the objects of the subclass look at the class template of the parent class in addition to the class template of the subclass.

2. Subclasses cannot directly access private member variables and methods in the parent class

Although the subclass will inherit the private member variables of the parent class, the subclass cannot directly access the inherited private member variables, but can access them through the inherited get/set method. as the picture shows:

3. In Java, the keyword of inheritance is "extends", that is, the subclass is not a subset of the parent class, but an "extension" of the parent class

After inheriting the parent class, the subclass can also define its own unique methods, which can be regarded as an extension of the function of the parent class.

4. Java supports multi-layer inheritance (inheritance system)

class A{}
class B extends A{}
class C extends B{}

illustrate:

  • Subclass and parent class are relative concepts

  • The top-level parent class is the Object class. All classes inherit Object by default as the parent class.

5. A parent class can have multiple subclasses at the same time

class A{}
class B extends A{}
class D extends A{}
class E extends A{}

6. Java only supports single inheritance, not multiple inheritance

public class A{}
class B extends A{}

//一个类只能有一个父类,不可以有多个直接父类。
class C extends B{} 	//ok
class C extends A,B...	//error

2.5 Exercises

**Exercise 1:**

Define a student class Student, which inherits from the Person class

Exercise 2:

(1) Define a ManKind class, including

  • Member variables int sex and int salary;

  • Method void manOrWoman(): Display "man" (sex1) or "woman" (sex0) according to the value of sex;

  • Method void employed(): Display "no job" (salary==0) or "job" (salary!=0) according to the value of salary.

(2) Define the class Kids to inherit ManKind and include

  • member variable int yearsOld;
  • The method printAge() prints the value of yearsOld.

(3) Define the class KidsTest, instantiate the object someKid of Kids in the main method of the class, and use this object to access the member variables and methods of its parent class.

**Exercise 3:** Implement the class according to the diagram below. Create an object of the Cylinder class in the CylinderTest class, set the base radius and height of the cylinder, and output the volume of the cylinder.

Guess you like

Origin blog.csdn.net/swx595182208/article/details/129999462