As I said before 封装
, let me talk about my 继承
understanding.
Inheritance, there must be some ideas to listen to this name. Inheritance can make the subclass have the attributes and methods of the parent class or redefine, append attributes and methods, etc.
This can make the reuse of code very simple. I can define a subclass with all the properties and methods of the parent class. At the same time, subclasses can also redefine methods and add attributes and methods, which can greatly reduce the workload.
Take the following code as an example:
There is now a parent class Animal
:
public class Animal {
public void getColor() {
System.out.println("Animal:color");
}
public void getName() {
System.out.println("Animal:name");
}
}
There are two subclasses Dog
:
public class Dog extends Animal{
public void getColor() {
System.out.println("Dogcolor");
}
public void getName() {
System.out.println("dogname");
}
public void bark() {
System.out.println("狗叫汪汪");
}
public void set() {
this.getColor(); //调用子类方法
super.getColor(); //调用父类方法
this.bark();
}
}
Cat
:
public class Cat extends Animal{
public void getColor() {
System.out.println("catcolor");
}
public void getName() {
System.out.println("catname");
}
public void jump() {
System.out.println("猫会跳");
}
public void set() {
this.getColor(); //调用子类方法
super.getColor(); //调用父类方法
this.jump();
}
}
Call Dog
class set
operating results after the method
invocation Cat
class set
operating results after the method:
It can be seen from the program, you can use super
keywords to achieve the realization of the parent class method.
A parent class can have multiple subclasses, and a subclass can only have one parent class, which is obvious.
A subclass can have other subclasses. For his subclasses, he is the parent class.
For example, there is now a Cat
subclass BlackCat
:
public class BlackCat extends Cat{
public void getColor() {
System.out.println("黑色");
}
public void set() {
this.getColor();
super.getColor();
}
}
The result:
the inherited characteristics:
1. non-parent child class has private
properties, methods.
2. Subclasses can have their own properties and methods, that is, subclasses can extend the parent class. This can also be seen from the code. Dog
Classes have Bark
methods, and Cat
classes have Jump
methods.
3. Subclasses can implement the parent class methods in their own way. You can use this
keywords to implement your own methods, and super
keywords to implement parent methods.
4. The inheritance of ava is single inheritance, but multiple inheritance is possible. Single inheritance means that a subclass can only inherit one parent class. Multiple inheritance is, for example, class A inherits class B, and class B inherits class C. It is the parent class of class B, and class B is the parent class of class A. This is a feature of Java inheritance that is different from C ++ inheritance.
5. Improve the coupling between the classes (disadvantages).