官术网_书友最值得收藏!

Inheritance

Inheritance is the ability to base an object or class on another one. There is a parent or base class, which provides the top-level behavior for an entity. Every subclass entity or child class that fulfills the criteria to be a part of the parent class can inherit from the parent class and add additional behavior as required.

Let's take a real-world example. If we think of a Vehicle as a parent class, we know a Vehicle can have certain properties and behaviors. For example, it has an engine, doors, and so on, and behavior-wise it can move. Now all entities that fulfill these criteria—for example, Car, Truck, Bike, and so on—can inherit from Vehicle and add on top of given properties and behavior. In other words, we can say that a Car is a type of Vehicle.

Let's see how this will look as code; we will first create a base class named Vehicle. The class has a single constructor, which accepts a String (the vehicle name):

public class Vehicle 
{
private Stringname;
public Vehicle(Stringname)
{
this.name=name;
}
}

Now we can create a Car class with a constructor. The Car class is derived from the Vehicle class, so it inherits and can access all the members and methods declared as protected or public in the base class:

public class Car extends Vehicle
{
public Car(String name)
{
super(name)
}
}
主站蜘蛛池模板: 凤山县| 太仓市| 奉贤区| 游戏| 五指山市| 突泉县| 公主岭市| 西乌珠穆沁旗| 乌拉特前旗| 鹿邑县| 邻水| 贵定县| 婺源县| 寿光市| 铁岭县| 乌什县| 墨竹工卡县| 美姑县| 奎屯市| 夏邑县| 克什克腾旗| 姜堰市| 浮梁县| 彭阳县| 进贤县| 三亚市| 文成县| 龙陵县| 嘉义市| 湖北省| 澜沧| 团风县| 宁南县| 台北县| 容城县| 鹤岗市| 徐州市| 罗城| 晋中市| 芜湖县| 建宁县|