- Design Patterns and Best Practices in Java
- Kamalmeet Singh Adrian Ianculescu LUCIAN PAUL TORJE
- 238字
- 2021-06-25 20:52:27
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)
}
}
- Spring Cloud Alibaba微服務架構設計與開發實戰
- jQuery從入門到精通 (軟件開發視頻大講堂)
- STM32F0實戰:基于HAL庫開發
- C語言程序設計
- 輕松上手2D游戲開發:Unity入門
- HTML5開發精要與實例詳解
- uni-app跨平臺開發與應用從入門到實踐
- Application Development with Parse using iOS SDK
- Visual Basic語言程序設計基礎(第3版)
- C語言程序設計
- 百萬在線:大型游戲服務端開發
- Java RESTful Web Service實戰
- Java核心編程
- C Primer Plus(第6版)中文版【最新修訂版】
- Java 7 Concurrency Cookbook