search
HomeJavajavaTutorialInheritance in Java: Concepts and Usage

    The concept of inheritance

    Inheritance means that the subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance domain and instance domain of the parent class. Method, or a subclass inherits a method from a parent class, so that the subclass has the same behavior as the parent class.

    Through inheritance, you can quickly create new classes, realize code reuse, improve program maintainability, save a lot of time in creating new classes, and improve development efficiency and quality.

    Benefits of inheritance:

    • Reduce code duplication

    • Improve code reusability

    • Facilitates function expansion

    ##✅Inheritance format:

    class A extends B{}

    A: subclass, Derived class, subclass, B: parent class, super class, base class, superclass

    reflects: Once subclass A inherits parent class B, subclass A obtains all the properties declared in parent class B Attributes and methods, in particular, attributes or methods declared as private in the parent class. After the subclass inherits the parent class, it is still considered to have obtained the private structure in the parent class. Only because of the influence of encapsulation, the subclass cannot directly call the parent class. The structure of the class is just that. After the subclass inherits the parent class, it can also declare its own unique attributes or methods: to realize the expansion of functions. A parent class can have multiple subclasses. Single inheritance of classes in Java: A class can only have one parent class. Subclasses are a relative concept. The parent class that a subclass directly inherits is called: direct parent. Class, the parent class that is indirectly inherited is called: indirect parent class. After the child class inherits the parent class, it obtains the attributes and methods declared in the direct parent class and all indirect parent classes.

    If we do not have an explicit declaration If it is the parent class of a class, then this class inherits from the java.lang.Object class. The Object class is the root parent class of all java classes.

    Points to note in inheritance:

    1. Subclasses cannot selectively inherit parent classes;

    2. Java does not support multiple inheritance, but a class can implement multiple interfaces, thereby overcoming the shortcomings of single inheritance;

    3. The construction method does not Will be inherited by subclasses, but the constructor of the parent class can be called from the subclass.

    For example

    class teacher{             //声明一个teacher类为父类
    	String name;      	   //定义父类的成员变量name、age   
    	int age;
    	void show(){           //定义父类成员方法,将成员变量输出
    		System.out.println(name); 	  
    		System.out.println(age); 
    	}
    }
    class Student extends teacher {     //声明一个Student类为子类并继承父类
    }
    public class myfirst {
    	public static void main(String[] args) {
    	System.out.println("学生");
    	Student student=new Student();     //声明一个Student类的实例对象student
    	student.name="Tom";                //子类调用父类的成员变量name并赋值
    	student.age=19;                    //子类调用父类的成员变量age并赋值
    	student.show();                    //子类调用父类的成员方法show
    	}
    }

    Rewriting of methods

    In actual applications, the functions of the child and parent classes we write are different, then we need to rewrite Or hide this method of the parent class.

    1 Rewriting: After a subclass inherits a parent class, it can overwrite methods with the same name and parameters in the parent class

    2 Application: After rewriting, when a subclass object is created , when a method with the same name and the same parameters in the child parent class is called through the child class object, what is actually executed is the child class overriding the parent class method

    3 Overriding provisions:

    method Statement:

    Permission modifier return value type method name (formal parameter list)

    The method in the subclass is called the overridden method, and the method in the parent class is called the overridden method The method written, the method name and formal parameter list of the method overridden by the subclass are the same as the method name and formal parameter list of the overridden method of the parent class, and the permission modifier of the method overridden by the subclass is not less than that of the overridden method of the parent class. Special case of method permission modifier: Subclasses cannot override methods declared as private permissions in the parent class

    About return value type:

    Return value type of the overridden method in the parent class is void, then the return value type of the method overridden by the subclass can only be void. The return value type of the overridden method of the parent class is type A, then the return value type of the method overridden by the subclass can be class A or Subclasses of class A

    The return value type of the overridden method of the parent class is a basic data type (for example: double), then the return value type of the method overridden by the subclass must be the same

    Methods with parameters of the same name in subclasses and parent classes must be declared as non-static before they can be overridden. If they are static, they cannot be overridden.

    For example,

    class A{
    	public void sayHello() {                      //输出英文欢迎
    		System.out.println("Hello,Welcome to Java!!!");
    	}
    	public void sayBye() {
    		System.out.println("GoodBye,everyone");
    	}
    }
    class B extends A {           
        public void sayHello() {                      //输出中文欢迎  
        	System.out.println("大家好,欢迎学习Java!!!");
        }
    }
    public class myfirst {
    	public static void main(String[] args) {
    	B b=new B();                                //创建子类B的一个实例对象,使用默认构造方法
    	b.sayHello();                               //调用子类中重写的方法
    	b.sayBye();                                 //调用父类中的方法
    	}
    }

    super keyword The use of

    super is understood as: of the parent class, super can be used to call properties, methods, and constructors.

    The use of super can be used in methods or constructors of subclasses. By using "super.property" or "super.method", you can explicitly call the properties or methods declared in the parent class. However, usually, we are used to omitting "super.

    Special cases: When a property with the same name is defined in a subclass and a parent class, if we want to call the property declared in the parent class in the child class, we must explicitly use the "super.property" method to indicate that the property declared in the parent class is being called. attribute. When a subclass overrides a method in the parent class, and we want to call the overridden method in the parent class in the method in the subclass, we must explicitly use the "super.method" method. Indicates that the method being overridden in the parent class is being called.

    super calls the constructor

    We can explicitly use "super (formal parameter list)" in the constructor of the subclass way to call the specified constructor declared in the parent class. The use of "super (formal parameter list)" must be declared in the first line of the subclass constructor. In the constructor of the class, we target "this (format parameter list)". Parameter list)" or super (formal parameter list)" can only choose one of the two and cannot appear at the same time. In the first line of the constructor, there is no explicit declaration of "this (formal parameter list)" or "super (formal parameter list)" ", call the constructor in the parent class

    For example

    package first;
    class A{
        public String name="张飞";         //添加成员变量
    	public void say() {                //添加成员方法say
    		System.out.println("我是父类A成员方法say");
    	}
    }
    class B extends A{
        public String name="关羽";         //与父类中同名的字段,隐藏父类
    	public void say(){                 //重写方法say
    		super.say();                   //使用super关键字调用父类中的方法
    		System.out.println("我是子类B成员方法say");
            System.out.println("父类的name名字:"+super.name); //使用super关键字访问父类中的变量
    	}
    }
    public class myfirst {
    	public static void main(String[] args) {
    	  B b=new B();                     //创建子类的一个实例对象
    	  b.say();                         //调用子类中重写的方法
    	  System.out.println("子类的name名字:"+b.name);   //调用子类中的name
    	}
    }

    The above is the detailed content of Inheritance in Java: Concepts and Usage. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

    Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

    完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

    一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

    Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

    详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

    本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

    Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

    java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

    封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

    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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment