java继承中的is-a_Java中的继承(IS-A关系)

java继承中的is-a

Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.

继承是面向对象编程的主要功能之一。 继承提供了一种机制,该机制允许一个类继承另一个类的属性 。 当一个类扩展另一个类时,它将继承所有非私有成员,包括字段和方法。 Java的继承可以通过父子关系(在Java语言中也称为父 (父 )和子类 ( 子类 ))得到最好的理解。

Inheritance defines is-a relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.

继承定义is-超级类及其子类之间关系。 extendsimplements关键字用于描述Java中的继承。

java继承中的is-a_Java中的继承(IS-A关系)_第1张图片

Let us see how extends keyword is used to achieve Inheritance. It shows super class and sub-class relationship.

让我们看看如何使用extends关键字实现继承。 它显示了超类和子类的关系。

class Vehicle
{
    ......
}
class Car extends Vehicle
{
    .......    //extends the property of vehicle class
}

Now based on above example. In OOPs term we can say that,

现在基于上面的示例。 用面向对象的术语,我们可以这样说:

  • Vehicle is super class of Car.

    车辆是超一流的汽车

  • Car is sub class of Vehicle.

    CarVehicle的子类。

  • Car IS-A Vehicle.

    汽车IS-A车辆。

继承目的 (Purpose of Inheritance)

  1. It promotes the code reusabilty i.e the same methods and variables which are defined in a parent/super/base class can be used in the child/sub/derived class.

    它促进了代码的可重用性,即可以在子/子/派生类中使用在父/上/基类中定义的相同方法和变量。

  2. It promotes polymorphism by allowing method overriding.

    它通过允许方法重写来促进多态性。

继承的缺点 (Disadvantages of Inheritance)

Main disadvantage of using inheritance is that the two classes (parent and child class) gets tightly coupled.

使用继承的主要缺点是两个类(父类和子类) 紧密耦合

This means that if we change code of parent class, it will affect to all the child classes which is inheriting/deriving

你可能感兴趣的:(java,设计模式,多态,类,编程语言)