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

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)
}
}
主站蜘蛛池模板: 阿拉善左旗| 普陀区| 杨浦区| 阳山县| 江孜县| 革吉县| 恩施市| 天镇县| 巴南区| 静安区| 靖远县| 桂林市| 枞阳县| 根河市| 勐海县| 汾西县| 吉木乃县| 洱源县| 陈巴尔虎旗| 长顺县| 宝应县| 资溪县| 沅陵县| 滁州市| 南丰县| 康平县| 清流县| 梅河口市| 苍山县| 东方市| 青铜峡市| 高要市| 桃源县| 潼南县| 嘉禾县| 牡丹江市| 平陆县| 绿春县| 济阳县| 玉环县| 玉屏|