Swift
// Defining a Base Classclass Vehicle {var currentSpeed = 0.0var description: String {return "traveling at \(currentSpeed) miles per hour"}func makeNoise() {// do nothing - an arbitrary vehicle doesn't necessarily make a noise}}let someVehicle = Vehicle()print("Vehicle: \(someVehicle.description)")// Vehicle: traveling at 0.0 miles per hour
// Subclassingclass SomeSubclass: SomeSuperclass {// subclass definition goes here}class Bicycle: Vehicle {var hasBasket = false}let bicycle = Bicycle()bicycle.hasBasket = true
bicycle.currentSpeed = 15.0print("Bicycle: \(bicycle.description)")// Bicycle: traveling at 15.0 miles per hour
// Subclasses can themselves be subclassedclass Tandem: Bicycle {var currentNumberOfPassengers = 0}let tandem = Tandem()tandem.hasBasket = truetandem.currentNumberOfPassengers = 2tandem.currentSpeed = 22.0print("Tandem: \(tandem.description)")// Tandem: traveling at 22.0 miles per hour
// Overridingclass Train: Vehicle {override func makeNoise() {print("Choo Choo")}}let train = Train()train.makeNoise()// Prints "Choo Choo"
// Overriding Property Getters and Settersclass Car: Vehicle {var gear = 1override var description: String {return super.description + " in gear \(gear)"}}let car = Car()car.currentSpeed = 25.0car.gear = 3print("Car: \(car.description)")// Car: traveling at 25.0 miles per hour in gear 3
JavaScript
// Defining a Base Classclass Vehicle {constructor() {this.currentSpeed = 0.0}get description() {return `traveling at ${currentSpeed} miles per hour`}function makeNoise() {// do nothing - an arbitrary vehicle doesn't necessarily make a noise}}let someVehicle = Vehicle()console.log(`Vehicle: ${someVehicle.description}`)// Vehicle: traveling at 0.0 miles per hour
// Subclassingclass SomeSubclass extends SomeSuperclass {contructor() {super();}// subclass definition goes here}class Bicycle extends Vehicle {contructor() {super();this.hasBasket = false}}let bicycle = Bicycle()bicycle.hasBasket = true
bicycle.currentSpeed = 15.0console.log(`Bicycle: ${bicycle.description}`)// Bicycle: traveling at 15.0 miles per hour
// Subclasses can themselves be subclassedclass Tandem extends Bicycle {contructor() {super();this.currentNumberOfPassengers = 0}}let tandem = Tandem()tandem.hasBasket = truetandem.currentNumberOfPassengers = 2tandem.currentSpeed = 22.0console.log("Tandem: \(tandem.description)")// Tandem: traveling at 22.0 miles per hour
// Overridingclass Train extends Vehicle {contructor() {super();this.currentNumberOfPassengers = 0}function makeNoise() {console.log("Choo Choo")}}let train = Train()train.makeNoise()// Prints "Choo Choo"
// Overriding Property Getters and Settersclass Car extends Vehicle {contructor() {super();this.gear = 1}get description() {return `${super.description} in gear ${gear}`}}let car = Car()car.currentSpeed = 25.0car.gear = 3console.log(`Car: ${car.description}`)// Car: traveling at 25.0 miles per hour in gear 3