1, inheritance (extends)
-
Let generate relationships between classes, parent child relationship
2, inheritance benefits
-
a: to improve the reusability of code
-
b: to improve the maintainability of the code
-
c: Let generate a relationship between classes, polymorphism is a prerequisite
3, inherited disadvantages
-
Type coupling is enhanced. Two classes very closely.
-
Principles for development: high cohesion and low coupling.
-
Classes and class relationships: Coupling
-
Cohesion: is their ability to accomplish something
3, inheritance case presentations:
-
Animals, cats, dogs
-
Define two properties (color, number of legs) two functions (eating, sleeping)
class Demo1_Extends {
public static void main(String[] args) {
Cat c = new Cat();
c.color = "花";
c.leg = 4;
c.eat();
c.sleep();
System.out.println(c.leg + "..." + c.color);
}
}
class Animal {
String color; //动物的颜色
int leg; //动物腿的个数
public void eat() { //吃饭的功能
System.out.println("吃饭");
}
public void sleep() { //睡觉的功能
System.out.println("睡觉");
}
}
class Cat extends Animal {
}
class Dog extends Animal {
}
/*
extends是继承的意思
Animal是父类
Cat和Dog都是子类
*/