Home  >  Article  >  Java  >  What is inheritance in Java? How to use inheritance in Java?

What is inheritance in Java? How to use inheritance in Java?

青灯夜游
青灯夜游forward
2018-10-20 18:01:003938browse

This article brings you an introduction to what Java inheritance is? How to use inheritance in Java? , teach novices how to use inheritance and understand the concept of inheritance. Master access modifiers and master the usage of final keyword. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Inheritance

Why use inheritance

First let’s take a look at these two classes:

public class Teacher {
    private int teachingAge;
    private String name;
    private int age;
    
    public void teach() {
        
    }
    public void seyHi() {
        System.out.println("我是:"+this.name);
    }
}
public class Student {
    private int studentNo;
    private String name;
    private int age;
    
    public void learn() {
        
    }
    public void seyHi() {
        System.out.println("我是:"+this.name);
    }
}

The Student class and the Teacher class have some similarities Properties and methods, these are duplicate codes. When there are a large number of classes in a program, a large amount of duplicate codes will be generated. Can these repeated codes be extracted and used by other classes to simplify them? That is to use to inherit .

After using inheritance optimization:

Create the inherit package

Parent class: (public code class)

package inherit;

public class People {
    private String name;
    private int age;
    
    public void sayHi() {
        System.out.println("我是:"+this.name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

Subclass: Student.java

package inherit;

public class Student extends People{
    private int studentNo;
    public void learn() {
        System.out.println("学习课程");
    }
    public int getStudentNo() {
        return studentNo;
    }
    public void setStudentNo(int studentNo) {
        this.studentNo = studentNo;
    }
}

Subclass: Teacher.java

package inherit;

public class Teacher extends People{
    private int teachingAge;
    
    public void teach() {
        System.out.println("教授课程");
    }
    
    public int getTeachingAge() {
        return teachingAge;
    }

    public void setTeachingAge(int teachingAge) {
        this.teachingAge = teachingAge;
    }
    
}

Test class:

package inherit;

public class TestInherit {
    public static void main(String[] args) {
        //创建Student对象
        Student stu=new Student();
        stu.setName("张三");//父类中继承过来的方法
        stu.learn();//子类中特有的方法
        stu.sayHi();
        //创建Teacher对象
        Teacher teacher=new Teacher();
        teacher.setName("汤尼");
        teacher.setTeachingAge(2);//子类中特有的方法
        teacher.sayHi();
    }
}

Observing the above example code we found:

1. All public codes of the subclass can be placed In the parent class

2. The subclass can have its own unique methods and attributes

3. Once the subclass inherits the parent class, it will have the attributes and methods of the parent class

4. Put the public code into the parent class to make it easier to modify the code uniformly

Inherited syntax

Keywords: extends

1. Write a parent class

public class 父类{
    //公共的属性和方法
}

2. Write a subclass and inherit the parent class

public class 子类 extends 父类{
    //子类特有的属性和方法
}

The subclass can only inherit one parent class

The subclass can access the parent Class members

If a subclass wants to access members of the parent class, it must use the super keyword. super represents the parent class object

to access the parent class structure Method:

super();//访问无参构造
super(参数);//访问有参构造

Access parent class attributes:

super.name;

Access parent class method:

super.print();

Access parent class constructor, must be called in child class constructor method, Must be the first sentence

super can only appear in methods and constructors of subclasses

super cannot access private members of the parent class

Knock knock: visit parent class members

Create the package visitparent and create the following class under the report
Parent class

package visitparent;

public class Animal {
    private String name;
    private int legs;
    
    public Animal() {
        this.name="无名";
        this.legs=4;
    }
    public Animal(String name,int legs) {
        this.name=name;
        this.legs=legs;
    }
    
    public void eat(String food) {
        System.out.println(name+" 吃食物:"+food);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLegs() {
        return legs;
    }

    public void setLegs(int legs) {
        this.legs = legs;
    }
    
}

Subclass

package visitparent;

public class Cat extends Animal{
    private String hairColor;//毛发颜色
    private int age;
    
    public Cat () {
        super();//调用父类无参
    }
    public Cat(String name,int legs,String hairColor,int age) {
        super(name, legs);//这里调用相当于重用父类构造方法了
        this.hairColor=hairColor;
        this.age=age;
        //super(name, legs);//去掉注释试试
        //this.name="无名";//去掉注释试试
    }
    public void catchMouse() {
        System.out.println(super.getName()+":抓老鼠");
    }
    
    public void paly() {
        System.out.println(super.getName()+" 玩累了。");
        super.eat("小鱼干");
    }

    public String getHairColor() {
        return hairColor;
    }

    public void setHairColor(String hairColor) {
        this.hairColor = hairColor;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

Subclasses cannot inherit private members of parent classes

Subclasses cannot inherit members of different packages that use default access permissions (the default access permissions do not write access modifiers )

Subclasses cannot inherit the constructor of the parent class

Execution process of multiple inheritance

When creating a subclass, the parent class doing what?

Create three classes below to observe the execution process. Class C inherits class B, and class B inherits class A.

A.java

public class A {
    public A() {
        System.out.println("A类的无参构造函数执行");
    }
}

B.java

public class B extends A{
    public B() {
        System.out.println("B类的无参构造函数执行");
    }
}

C.java

public class C extends B{
    public C() {
        System.out.println("C类的无参构造函数执行");
    }
}

TestRunFlow.java test class, showing the running results

public class TestRunFlow {
    public static void main(String[] args) {
        C c=new C();
    }
}

The running result is:

The no-parameter constructor of class A is executed
The no-parameter constructor of class B is executed
The no-parameter constructor of class C is executed

If the subclass constructor explicitly calls the corresponding constructor of the parent class through super, the parent class's parameterless constructor will not be executed.

The subclass constructor will call the parent class's parameterless constructor by default. Method

Call the parameterless constructor of the parent class until the parameterless constructor of the top-level parent class Object class is executed

According to the above rules, judge Can the following code be compiled and passed

parent class

public class Pet {
    private String name;
    public Pet(String name) {
        this.name=name;
    }
}

subclass

public class Dog extends Pet{
}

The answer is no. There are only parameterized constructors and no parameterless constructors in the parent class. No code in the class has an implicit parameterless constructor by default. The parameterless constructor of the subclass calls the parameterless constructor of the parent class by default. However, there is no parameterless constructor in the parent class, so an error is reported in the child class.

Solution: 1. Explicitly add a parameterless constructor in the parent class, 2. Explicitly call the parent class's parameterized constructor in the subclass constructor.

Access modifiers in java

The access modifier protected can modify properties and methods. After modification, this class, subclasses, and the same package can access them.

##Default (friendly)√√protected√√√public√√√√

方法重写

在"继承优化后"的代码中,Teacher 继承了 People 类,(忘记代码可以翻回去再看一遍) People 类中有个一个打招呼的方法 sayHi() 用于输出人的名字,但是 Teacher 调用这个方法并不能打印出 Teacher 的属性 teachingAge 的值,但是我们还想用这个方法实现这个功能,应该怎么办呢?

我们可以使用 方法重写 解决这个问题,修改子类 Teacher 中的代码,下面看一下使用方法重写后的效果。

Teacher.java

package inherit;

public class Teacher extends People{
    //省略其他属性
    
    @Override
    public void sayHi() {
        System.out.println("我是:"+super.getName()+" ,从事教育行业 "+this.teachingAge+" 年了。");
    }

    //省略其他方法、getter、setter
}

在 Eclipse 中重写某方法的快捷键是 Alt+Shift+S+V ,按完后选择要重写的方法

在 Idea 中重写某方法的快捷键是 Ctrl+O ,按完后选择要重写的方法

@Override 注解的作用, 用来检测是否符合重写规则,不符合重写规则将报错,这个注解可以不写

构造方法不能重写,因为构造方法不能被继承

方法重写的规则:

1.方法名相同

2.参数列表相同

3.返回值类型相同或者是其子类

4.访问权限不能严于父类

final 关键字的使用

1.final 修饰变量后变为常量

private static final long serialVersionUID = -6849794470754667710L;

2.final 修饰类后,该类不能被继承

package java.lang;
public final class Math {
    //省略属性和方法……
}

3.final 修饰方法后,该方法不能被重写

public final void teach() {
        System.out.println("教授课程");
    }

4.final 修饰创建的对象后,该对像不能再次实例化(可以修改属性)

final Teacher teacher=new Teacher();
teacher.setName("汤尼");
//teacher=new Teacher();//去掉注释试试

String 类就是一个典型的被 final 修饰的类

Access modifier This class Same package Subclass Others
private





The above is the detailed content of What is inheritance in Java? How to use inheritance in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete