1. 继承

1.1 概念

  • 1.1.1 定义:子类通过 extends 关键字继承父类,自动获得父类的非私有属性和方法,无需重复编写
  • 1.1.2 作用:提高代码复用性,减少重复代码

1.2 语法格式

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

1.3 继承规则

  • 1.3.1 单根继承:Java 中一个类只能继承一个父类,不支持多继承
  • 1.3.2 继承内容:子类继承父类所有 publicprotected 修饰的属性和方法,private 修饰的不能继承
  • 1.3.3 示例
  class Animal {
      public int age;
      public String type;
 
      public void eat() {
          System.out.println("吸收营养");
      }
 
      public void move() {
          System.out.println("会移动");
      }
  }
 
  class Cat extends Animal {
      // 自动继承 age、type、eat()、move()
  }
 
  class Dog extends Animal {
      // 自动继承 age、type、eat()、move()
  }
  • 1.3.4 调用继承的方法:子类对象可以直接调用父类的非私有方法
  Cat cat = new Cat();
  cat.move(); // 继承自 Animal
 
  Dog dog = new Dog();
  dog.eat();  // 继承自 Animal

2. 示例代码

package com.itszt.day04;
 
public class Demo07 {
    public static void main(String[] args) {
        Cat cat = new Cat();
        cat.move(); // 继承自 Animal:会移动
 
        Dog dog = new Dog();
        dog.eat();  // 继承自 Animal:吸收营养
    }
}
 
class Animal {
    public int age;
    public String type;
 
    public void eat() {
        System.out.println("吸收营养");
    }
 
    public void move() {
        System.out.println("会移动");
    }
}
 
class Cat extends Animal {
}
 
class Dog extends Animal {
}

3. 总结

知识点核心要点
继承关键字extends
继承内容父类非私有(public / protected)的属性和方法
不继承内容private 修饰的属性和方法
单根继承一个子类只能继承一个父类
作用减少重复代码,提高复用性