Home Java JavaBase Detailed explanation of inheritance in Java

Detailed explanation of inheritance in Java

Nov 25, 2019 pm 04:45 PM
java

Detailed explanation of inheritance in Java

Basic concepts of java inheritance and synthesis

Inheritance: You can construct a new class based on an existing class. Inheriting existing classes allows you to reuse the methods and fields of these classes. On this basis, new methods and fields can be added, thereby expanding the functionality of the class.

Synthesis: Creating an original object in a new class is called synthesis. This way you can reuse existing code without changing its form.

Recommended related video tutorials: java video tutorial

1. Inherited syntax

The keyword extends indicates that the new class is derived to an existing class. The existing class is called a parent class or base class, and the new class is called a subclass or derived class. For example:

class Student extends Person {

}
Copy after login

The class Student inherits Person. The Person class is called the parent class or base class, and the Student class is called the subclass or derived class.

2. Syntax of synthesis

Synthesis is relatively simple, which is to create an existing class within a class.

class Student {
    Dog dog;
}
Copy after login

Updating modeling

1. Basic concept

The role of inheritance lies in the duplication of code use. Since inheritance means that all methods of the parent class can also be used in the child class, messages sent to the parent class can also be sent to the derived class. If there is an eat method in the Person class, then there will also be this method in the Student class, which means that the Student object is also a type of Person.

class Person {
    public void eat() {
        System.out.println("eat");
    }

    static void show(Person p) {
        p.eat();
    }
}
public class Student extends Person{
    public static void main(String[] args) {
        Student s = new Student();
        Person.show(s);     // ①
    }
}
Copy after login

[Run results]:
eat

The show method defined in Person is used to receive the Person handle, but what is received at ① is a reference to the Student object. This is because the Student object is also a Person object. In the show method, the incoming handle (object reference) can be a Person object and a Person-derived class object. This behavior of converting a Student handle into a Person handle is called upcasting.

2. Why do we need to trace back the shape?

Why do we intentionally ignore the object type that calls it when calling eat? It seems more intuitive and easier to understand if the show method simply obtains the Student handle, but that would cause each new class derived from the Person class to implement its own show method:

class Value {
    private int count = 1;

    private Value(int count) {
        this.count = count;
    }

    public static final Value
            v1 = new Value(1),
            v2 = new Value(2),
            v3 = new Value(3);
}

class Person {

    public void eat(Value v) {
        System.out.println("Person.eat()");
    }
}

class Teacher extends Person {
    public void eat(Value v) {
        System.out.println("Teacher.eat()");
    }
}

class Student extends Person {
    public void eat(Value v) {
        System.out.println("Student.eat()");
    }
}

public class UpcastingDemo {
    public static void show(Student s) {
        s.eat(Value.v1);
    }

    public static void show(Teacher t) {
        t.eat(Value.v1);
    }

    public static void show(Person p) {
        p.eat(Value.v1);
    }

    public static void main(String[] args) {
        Student s = new Student();
        Teacher t = new Teacher();
        Person p = new Person();
        show(s);
        show(t);
        show(p);
    }
}
Copy after login

This approach is obvious The disadvantage is that closely related methods must be defined for each derived class of the Person class, resulting in a lot of duplicate code. On the other hand, if you forget to overload a method, no error will be reported. The three show methods in the above example can be combined into one:

public static void show(Person p) {
     p.eat(Value.v1);
}
Copy after login
Copy after login

Dynamic binding

When show(s) is executed, The output result is Student.eat(), which is indeed the desired result, but it does not seem to be executed in the form we want. Let’s take a look at the show method:

public static void show(Person p) {
     p.eat(Value.v1);
}
Copy after login
Copy after login

It receives the Person handle. When executed When show(s), how does it know that the Person handle points to a Student object instead of a Teacher object? The compiler has no way of knowing, which involves the binding issue explained next.

1. Binding of method calls

Connecting a method with a method body is called binding. If binding is performed before running, it is called "early binding". In the above example, when there is only one Person handle, the compiler does not know which method to call. Java implements a method calling mechanism that can determine the type of an object during runtime and then call the corresponding method. This binding, which is performed during runtime and is based on the type of the object, is called dynamic binding. Unless a method is declared final, all methods in Java are dynamically bound.

Use a picture to represent the inheritance relationship of upstream modeling:

Detailed explanation of inheritance in Java

Summarize it in code:

Shape s = new Shape();
Copy after login
Copy after login

According to the inheritance relationship, create It is legal to assign the Circle object handle to a Shape because Circle is a type of Shape.

When one of the base class methods is called:

Shape s = new Shape();
Copy after login
Copy after login

At this time, Circle.draw() is called, which is due to dynamic binding.

class Person {
    void eat() {}
    void speak() {}
}
class Boy extends Person {
    void eat() {
        System.out.println("Boy.eat()");
    }
    void speak() {
        System.out.println("Boy.speak()");
    }
}
class Girl extends Person {
    void eat() {
        System.out.println("Girl.eat()");
    }
    void speak() {
        System.out.println("Girl.speak()");
    }
}
public class Persons {
    public static Person randPerson() {
        switch ((int)(Math.random() * 2)) {
        default:
        case 0:
            return new Boy();
        case 1:
            return new Girl();
        }
    }
    public static void main(String[] args) {
        Person[] p = new Person[4];
        for (int i = 0; i < p.length; i++) {
            p[i] = randPerson();    // 随机生成Boy或Girl
        }
        for (int i = 0; i < p.length; i++) {
            p[i].eat();
        }
    }
}
Copy after login

Person has established a common interface for all classes derived from Person, and all derived classes have two behaviors: eat and speak. Derived classes override these definitions, redefining both behaviors.

In the main class, randPerson randomly selects the handle of the Person object. **Appeal shaping occurs in the return statement. The **return statement obtains a Boy or Girl handle and returns it as a Person type. At this time, we don’t know the specific type, we only know that it is a Person object handle.

Call the randPerson method in the main method to fill in the Person object into the array, but I don’t know the specific situation. When the eat method of each element of the array is called, the role of dynamic binding is to execute the redefined method of the object.

However, dynamic binding has a prerequisite. The binding method must exist in the base class, otherwise it cannot be compiled.

class Person {
    void eat() {
        System.out.println("Person.eat()");
    }
}
class Boy extends Person {
    void eat() {
        System.out.println("Boy.eat()");
    }
    void speak() {
        System.out.println("Boy.speak()");
    }
}
public class Persons {
    public static void main(String[] args) {
        Person p = new Boy();
        p.eat();
        p.speak();  // The method speak() is undefined for the type Person
    }
}
Copy after login

如果子类中没有定义覆盖方法,则会调用父类中的方法:

class Person {
    void eat() {
        System.out.println("Person.eat()");
    }
}
class Boy extends Person {
}
public class Persons {
    public static void main(String[] args) {
        Person p = new Boy();
        p.eat();
    }
}
Copy after login

【运行结果】:
Person.eat()

2.静态方法的绑定

将上面的方法都加上static关键字,变成静态方法:

class Person {
    static void eat() {
        System.out.println("Person.eat()");
    }
    static void speak() {
        System.out.println("Person.speak()");
    }
}
class Boy extends Person {
    static void eat() {
        System.out.println("Boy.eat()");
    }
    static void speak() {
        System.out.println("Boy.speak()");
    }
}
class Girl extends Person {
    static void eat() {
        System.out.println("Girl.eat()");
    }
    static void speak() {
        System.out.println("Girl.speak()");
    }
}
public class Persons {
    public static Person randPerson() {
        switch ((int)(Math.random() * 2)) {
        default:
        case 0:
            return new Boy();
        case 1:
            return new Girl();
        }
    }
    public static void main(String[] args) {
        Person[] p = new Person[4];
        for (int i = 0; i < p.length; i++) {
            p[i] = randPerson();    // 随机生成Boy或Girl
        }
        for (int i = 0; i < p.length; i++) {
            p[i].eat();
        }
    }
}
Copy after login

【运行结果】:

Person.eat() 
Person.eat() 
Person.eat() 
Person.eat()
Copy after login

观察结果,对于静态方法而言,不管父类引用指向的什么子类对象,调用的都是父类的方法。

更多java相关文章请关注java基础教程栏目。

The above is the detailed content of Detailed explanation of inheritance in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles