Home Java javaTutorial What is inheritance in java? How to implement inheritance

What is inheritance in java? How to implement inheritance

Nov 26, 2018 pm 06:02 PM
java inherit

This article brings you an introduction to what inheritance is in Java? How to implement inheritance. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is inheritance in java?

Inheritance in Java is a mechanism by which an object obtains all properties and behaviors of its parent object. It is an important part of object-oriented programming system (OOP).

The idea of ​​inheritance in Java is to create new classes based on existing classes. Inheriting from an existing class allows you to reuse methods and fields of the parent class. Additionally, new methods and fields can be added to the current class. [Related video tutorial recommendations: JavaTutorial]

Inheritance represents the IS-A relationship, also known as the parent-child relationship.

Terms used in inheritance

1. Class: A class is a group of objects with common attributes. It is a template or blueprint for creating objects.

2. Subclass: A subclass is a class that inherits other classes. It is also called a derived class, extended class or subclass.

3. Super class/parent class: Super class is a class from which subclasses inherit functions. It is also called base class or parent class.

4. Reusability: As the name specifies, reusability is a mechanism that helps you reuse the fields and methods of an existing class when creating a new class. You can use the same fields and methods that were defined in the previous lesson.

Why use inheritance in java?

1. Method rewriting can be achieved (this can achieve runtime polymorphism).

2. Inheritance allows us to reuse code, which improves the reusability of Java applications.

The implementation of Java inheritance

The basic syntax of Java inheritance

To inherit a class, We use the extends keyword. Class XYZ here is a subclass, and class ABC is a parent class. Class XYZ inherits the properties and methods of class ABC.

class Subclass-name extends Superclass-name  
{  
   //方法和字段  
}
Copy after login

extends keyword indicates that we are creating a new class derived from an existing class. The meaning of "extends" is to increase functionality.

In Java terminology, the inherited class is called the parent class or super class, and the new class is called a subclass.

Inheritance example:

In the following inheritance example, class Bicycle is a base class, class MountainBike is a derived class, which extends the Bicycle class, and class Test is a driver class that runs the program.

//用java程序来说明
// 继承的概念
  
// 基类
class Bicycle  
{ 
    // Bicycle类有两个字段
    public int gear; 
    public int speed; 
          
    // Bicycle类有一个构造函数
    public Bicycle(int gear, int speed) 
    { 
        this.gear = gear; 
        this.speed = speed; 
    } 
          
    // Bicycle类 有三种方法
    public void applyBrake(int decrement) 
    { 
        speed -= decrement; 
    } 
          
    public void speedUp(int increment) 
    { 
        speed += increment; 
    } 
      
    // toString()方法来输出 Bicycle类信息
    public String toString()  
    { 
        return("没有的齿轮个数是 "+gear 
                +"\n"
                + "自行车的速度是"+speed); 
    }  
} 
  
// 派生类
class MountainBike extends Bicycle  
{ 
      
    // MountainBike子类增加一个字段
    public int seatHeight; 
  
    // MountainBike子类  有一种构造函数
    public MountainBike(int gear,int speed, 
                        int startHeight) 
    { 
        // 调用基类(Bicycle类)构造函数
        super(gear, speed); 
        seatHeight = startHeight; 
    }  
          
    // MountainBike子类增加一个方法
    public void setHeight(int newValue) 
    { 
        seatHeight = newValue; 
    }  
      
    // 重写toString()方法
    // 输出跟多Bicycle类信息 
    @Override
    public String toString() 
    { 
        return (super.toString()+ 
                "\n 座位高度为 "+seatHeight); 
    } 
      
} 
  
// 驱动程序类
public class Test  
{ 
    public static void main(String args[])  
    { 
          
        MountainBike mb = new MountainBike(3, 100, 25); 
        System.out.println(mb.toString()); 
              
    } 
}
Copy after login

Output:

What is inheritance in java? How to implement inheritance

Inherited types in Java

In the class Basically, there can be three types of inheritance in Java: single, multi-level and hierarchical.

1. Single inheritance: In single inheritance, a subclass inherits the characteristics of a superclass. In the diagram below, class A acts as a base class from which class B is derived.

What is inheritance in java? How to implement inheritance

2. Multi-level inheritance: In multi-level inheritance, the derived class will inherit the base class, and the derived class will also serve as the base class for other classes. . In the image below, class A is used as a base class for derived class B, which in turn is used as a base class for derived class C. In Java, a class cannot directly access members of its grandparents.

What is inheritance in java? How to implement inheritance

3. Hierarchical inheritance: In hierarchical inheritance, a class acts as a superclass (base class) for multiple subclasses. In the image below, class A acts as a base class from which classes B, C and D are derived.

What is inheritance in java? How to implement inheritance

4. Multiple inheritance (through interface) : In multiple inheritance, a class can have multiple superclasses and inherit from all parent classes. Function. Please note that Java does not support multiple inheritance and classes. In java, we can only achieve multiple inheritance through Interfaces. In the image below, class C comes from interfaces A and B.

What is inheritance in java? How to implement inheritance

5. Mixed inheritance (through interface) : It is a mixture of two or more of the above types of inheritance. Since Java does not support multiple inheritance using classes, classes cannot implement mixed inheritance. In java, we can only achieve mixed inheritance through Interfaces.

What is inheritance in java? How to implement inheritance

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

The above is the detailed content of What is inheritance in java? How to implement inheritance. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles