search
HomeJavajavaTutorialWhat is inheritance in java? How to implement inheritance

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  
{  
   //方法和字段  
}

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()); 
              
    } 
}

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
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
Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

Is Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksIs Java Truly Platform Independent? How 'Write Once, Run Anywhere' WorksMay 13, 2025 am 12:03 AM

JavaisnotentirelyplatformindependentduetoJVMvariationsandnativecodeintegration,butitlargelyupholdsitsWORApromise.1)JavacompilestobytecoderunbytheJVM,allowingcross-platformexecution.2)However,eachplatformrequiresaspecificJVM,anddifferencesinJVMimpleme

Demystifying the JVM: Your Key to Understanding Java ExecutionDemystifying the JVM: Your Key to Understanding Java ExecutionMay 13, 2025 am 12:02 AM

TheJavaVirtualMachine(JVM)isanabstractcomputingmachinecrucialforJavaexecutionasitrunsJavabytecode,enablingthe"writeonce,runanywhere"capability.TheJVM'skeycomponentsinclude:1)ClassLoader,whichloads,links,andinitializesclasses;2)RuntimeDataAr

Is java still a good language based on new features?Is java still a good language based on new features?May 12, 2025 am 12:12 AM

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

What Makes Java Great? Key Features and BenefitsWhat Makes Java Great? Key Features and BenefitsMay 12, 2025 am 12:11 AM

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Top 5 Java Features: Examples and ExplanationsTop 5 Java Features: Examples and ExplanationsMay 12, 2025 am 12:09 AM

The five major features of Java are polymorphism, Lambda expressions, StreamsAPI, generics and exception handling. 1. Polymorphism allows objects of different classes to be used as objects of common base classes. 2. Lambda expressions make the code more concise, especially suitable for handling collections and streams. 3.StreamsAPI efficiently processes large data sets and supports declarative operations. 4. Generics provide type safety and reusability, and type errors are caught during compilation. 5. Exception handling helps handle errors elegantly and write reliable software.

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function