extends继承
继承可以使得子类型具有父类型的属性和方法或者重新定义、追加属性和方法等
1.使用
1.1 为什么使用继承:
达到类层面的复用
1.2 如何使用继承:
在子类的类名后面加上 extends 父类的类名
2.特点:
1. 子类一旦继承父类,就拥有了父类中的内容
2. 一个类可以有多个子类,一个子类只能有一个父类 (单继承 多实现)
3. 子类是父类的延续加扩展
父类||基类||超类 ------ 被继承的类
子类||派生类 ------ 继承其他类的类
3.优点:
提高代码的复用性
单继承的优点: 使用简单
单继承的缺点: 不便于后期维护
面向对象设计原则之一:开闭原则 对修改关闭,对扩展开放
4.没卵用的代码
public class TestExtends {
public static void main(String[] args) {
// 动物 恒温动物 蛇 人 哺乳动物 变温动物
Animal animal = new Animal();
WarmBloodedAnimals warmBloodedAnimals = new WarmBloodedAnimals();
Snake snake = new Snake();
Person person = new Person();
Mammal mammal = new Mammal();
Ectotherm ectotherm = new Ectotherm();
/
System.out.println();
System.out.println("动物");
animal.move();
System.out.println();
System.out.println("恒温动物");
warmBloodedAnimals.move();
System.out.println(warmBloodedAnimals.blooded);
System.out.println();
System.out.println("变温动物");
ectotherm.move();
System.out.println(ectotherm.blooded);
System.out.println();
System.out.println("哺乳动物");
mammal.move();
System.out.println(mammal.blooded);
System.out.println();
System.out.println("蛇");
snake.move();
System.out.println(snake.blooded);
System.out.println();
System.out.println("人类");
person.move();
System.out.println(person.blooded);
System.out.println(person.reproduction);
person.playGame();
}
}
class Animal {// 动物
public void move() {// 方法---- 移动
System.out.println("是可移动的");
}
}
class Mammal extends WarmBloodedAnimals {// 哺乳动物
}
class Person extends Mammal {// 人类
String reproduction = "Viviparous(胎生的)";// 繁殖
public void playGame() {
System.out.println("沉迷游戏");
}
}
class Snake extends Ectotherm {// 蛇
}
class Ectotherm extends Animal {// 变温动物
String blooded = "!Thermostatic(冷血的)";// 冷血的||变温的
}
class WarmBloodedAnimals extends Animal {// 恒温动物
String blooded = "Thermostatic(恒温的)";// 血液---- 恒温的(恒温动物)
}