Swift: Simple inheritance with a method

This entry is part 21 of 41 in the series Swift

This is an inherited class with a call to the parent’s method.

class Person {
    var name = ""
    var age = 0
        self.name = ""
        self.age = 0
        self.name = name
        self.age = age
    func printIntro(){
        print("My name is \(self.name) My age is \(self.age)")


class Student : Person {

var student = Student(name: "Taylor Swift", age: 20)



Swift: Inheritance

This entry is part 17 of 41 in the series Swift

Here we set up a parent class called Music and its inherited class called Rock.  Notice how we need to use super.init to initialise the 2 inherited members from the parent Music class.

import UIKit

class Music {
    var totalAlbums: Int
    var price: Double
    init(tAlb: Int, pMusic: Double) {
        self.totalAlbums = tAlb
        self.price = pMusic

class Rock : Music{
    var numRock: Int
    var rockPrice: Double
    init(totalAlbums: Int, price: Double, nRock: Int, rPrice: Double) {
        self.numRock = nRock
        self.rockPrice = rPrice
        super.init(tAlb : totalAlbums, pMusic : price)


var mAlbums = 1000
var mPrice = 12.50

let musicGenre = Music(tAlb: mAlbums, pMusic: mPrice)


var rAlbums = 300
var rPrice = 15.60

let rockGenre = Rock(totalAlbums: mAlbums, price: mPrice, nRock: rAlbums, rPrice: rPrice)

//Now we can access the 2 members in its parent class



C++: Inheritance

This entry is part 44 of 61 in the series C++

In a programming language like C++, inheritance is one of the core ideas of Object-Oriented program.

In inheritance, the derived class inherits the behaviors and attributes of its base class.

In our earlier examples, we have built a Rock class and a Country class.  In a way, pop or rock are just a genre in music.

We can understand pop or rock as a subclass of music.  So in an object-oriented program, we can build a base class called Music and another 2 derived classes called Pop or Rock.

Consider the following example.

#include <cstdlib>
#include <iostream>

using namespace std;

// Base class

class Music {

    void setSinger(string s) {
        singer = s;

    void setTitle(string t) {
        title = t;
    string singer;
    string title;

// Derived class

class Rock : public Music {

    int Display() {
        cout << singer << " singing " << title;      
        return 0;

class Pop : public Music {

    int Show() {
        cout << singer << " top 10 hit " << title;      
        return 0;

int main(void) {
    Rock rock;

    rock.setSinger("Rod Stewart");
    rock.setTitle("I Was Only Joking");

    cout << rock.Display() << endl;
    Pop pop;
    pop.setSinger("Taylor Swift");
    pop.setTitle("Blank Space");
    cout << pop.Show() << endl;

    return 0;

In line 19, we have declared 2 data members as protected.  This will allow them to be accessed by its derived class Rock or Pop.



Python Objects (or a Bike and a Wheel)

This entry is part 7 of 8 in the series Python

When I first tried to teach myself programming, I bought a Java book that started teaching object-oriented programming (OOP) by describing an object (a bicycle), which had properties (wheels, pedals, etc), and state (moving or stopped).  I said whaah?!  Why am I learning about a bike and whether it’s moving or not.

Needless to say, I was completely befuddled and had no idea what I was doing or how to relate this bike concept.  Funny enough, a handful of years later a co-worker of mine described programming in almost exactly the same way.  It made as much of no sense as it did the first time.

The point in this initial ramble of mine is to promise you I won’t try to explain programming and OOP by using your first grade tricycle.

I like to think of OOP as a useful way to combine similar sets of code/logic so you can use it over and over without rewriting it.  From How To Become A Hacker (not the breaking into things type, but hacker as in building killer software), Eric S. Raymond writes:

Hackers (and creative people in general) should never be bored or have to drudge at stupid repetitive work, because when this happens it means they aren’t doing what only they can do — solve new problems. This wastefulness hurts everybody. Therefore boredom and drudgery are not just unpleasant but actually evil.



To behave like a hacker, you have to believe this enough to want to automate away the boring bits as much as possible, not just for yourself but for everybody else (especially other hackers).

OOP is useful so you don’t have to write the same thing, over and over again.  The example I like to use is writing a banking application.  First I’ll briefly explain a core part of DRY (Don’t Repeat Yourself) as functions.  If you have a for loop where you perform the same logic over a list, you can separate that logic into a function so you only write it once, but you can call it as many times as you need.

"""We're going to print abreviated titles
from a list of titles
def short_title(title):
    new_title = ''
    if len(title) > 20: 
        new_title = title[:21]+'...'
        new_title = title

    return new_title

titles = [ 
    'Here is Title 1',
    'Title 2', 
    "A longer title that won't fit.",
    'Something a bit longer than we want'

for title in titles:
    print short_title(title)

To declare a function, we use the keyword def to declare (or define) a function.  title in def short_title(title): is a parameter that is passed into this function, which we use later to create a short title.  The gist of short_title is to return an abbreviated title if it’s longer than 20 characters.  Don’t worry too much about the details, just try to understand that the short_title function allows us to repeat creating an abbreviated title and use it anywhere else we need it.

The output, in case you were curious:

$ python function.py 
Here is Title 1
Title 2
A longer title that w...
Something a bit longe...

Next lesson we’ll go over the following code about the rich, poor, and greedy:

# bank.py
class Person(object):
    """This is the base class that represents
    a Person
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def get_full_name(self):
        return self.first_name +' '+ self.last_name

class Employee(Person):
    """Since an employee is a Person, we indicate
    that we are a Person by declaring
    class Employee(Person):
    The item inside of () shows we inherit from
    def __init__(self, fname, lname, age, salary, manager):
        Person.__init__(self, first_name=fname, last_name=lname, age=age)
        self.salary = salary
        self.manager = manager

    def get_manager_salary(self):
        return self.manager.salary

    def is_owner(self):
        return True if self.manager is not None else False

class Customer(Person):
    """A Customer is also a Person
    which means we also have a first and last name
    as well as an age
    def __init__(self, first_name, last_name, age, bank_account):
        Person.__init__(self, first_name, last_name, age=age)
        self.bank_account = bank_account

    def get_account_balance(self):
        return self.bank_account.balance

    def deposit(self, amount):
        # We return the new account balance
        return self.bank_account.increase_cash(amount)

    def spend(self, amount):
        return self.bank_account.decrease_cash(amount)

class BankAccount(object):
    """A class that represents a bank
    def __init__(self, balance, manager):
        self.balance = balance
        self.manager = manager

    def decrease_cash(self, spent_money):
        self.balance -= spent_money
        return self.balance

    def increase_cash(self, money):
        self.balance += money
        return self.balance

bank_manager = Employee('Scrooge', 'McMuffins', salary=1000000, age=99, manager=None)
rich_bank_account = BankAccount(1000, bank_manager)
rich_customer = Customer('Rich', 'Person', age=205, bank_account=rich_bank_account)

print 'The bank manager for your bank is %s'%(bank_manager.get_full_name())
print 'Your account has $%d in it'%(rich_bank_account.balance)

interest_payment = 2500
print '%s\'s account earns $%d of interest'%(rich_customer.get_full_name(), interest_payment)
new_balance = rich_bank_account.increase_cash(interest_payment)
print '%s\'s new balance is $%d'%(rich_customer.get_full_name(), new_balance)
print '%s\'s age is %d years old'%(rich_customer.get_full_name(), rich_customer.age)

print '%s spends a little money'%(rich_customer.get_full_name())
print '%s now has $%d'%(rich_customer.get_full_name(), rich_customer.get_account_balance())

# He has the same mean bank manager as the rich person!
poor_account = BankAccount(10, manager=bank_manager)
poor_customer = Customer('Poor', 'Person', 105, poor_account)

print '%s starts with $%d'%(poor_customer.get_full_name(), poor_account.balance)
print '%s steals money from %s'%(bank_manager.get_full_name(), poor_customer.get_full_name())
print '%s now only has $%d'%(poor_customer.get_full_name(), poor_customer.get_account_balance())

The output for this code is below:

$ python bank.py 
The bank manager for your bank is Scrooge McMuffins
Your account has $1000 in it
Rich Person's account earns $2500 of interest
Rich Person's new balance is $3500
Rich Person's age is 205 years old
Rich Person spends a little money
Rich Person now has $3400
Poor Person starts with $10
Scrooge McMuffins steals money from Poor Person
Poor Person now only has $5

Can you piece it together before we talk about it?  Comment below with any thoughts….


Java: Basic concept of inheritance

This entry is part 38 of 54 in the series Learn Java

Inheritance is the ability of a class to derive something specific from a generic class.

The generic class is called super class or base class or parent class and the specific class is known as child class or subclass or derived class.

package javaapplication32;

class Book {

    public void print_bk() {
        System.out.println("This is the parent book class");

class LibraryBook extends Book {

    public void print_lbk() {
        System.out.println("This is the library book class");

public class MainBook {

    public static void main(String args[]) {
        Book bk = new Book();
        LibraryBook lbk = new LibraryBook();

In this example, the instance lbk is an instance of LibraryBook.  However, since LibraryBook is a subclass of Book, we are able to use lbk to access the method defined in class Book.