44.9k views
4 votes
Explain a situation that we would want to use a class in and alsoexplain a situation that we would want to use an inheritedclass.

1 Answer

2 votes

Answer:

Classes are a useful (and fundamental) tool in object oriented programming.

The use-case for a class will typically fall into when you have a set of information that you aim to store and, have a need for methods that will build upon that information. This example class (written in python, because I'm lazy but the concepts extend well into other tongues) helps to elaborate on this:

# I am going to assume you are not using python

# And explain a few things about it.

# This class is meant to represent an order

# For say, a fast food or pizza chain.

class order {

lastOrder = 0 # In python this is a static variable of the class.

def __init__(self, orderID=None, food, complete=False, price):

if orderID == None:

order.lastOrder += 1

self.orderID = order.lastOrder

else:

self.orderID = orderID

self.__food = food

self.__complete = complete

self.__price = price

# Double underscore vars in python are similar to

# Private variables in other languages.

def setStatus(complete): # Setter to set if order is completed.

# Variable to true.

self.__complete = complete

def isComplete(): # Getter, to say if it's completed.

return self.__complete

}

myOrder = new order(

food=("Cheese Pizza", "Bread Sticks", "Meatball Sub")

price=38.5,

)

# Don't mind the tuple (why I used parenthesis, basically just an immutable #list.

# Customer gets there food and pays:

myOrder.setStatus(True) # Order is complete.

That's great and all, but what if we want other options for takeout, dine in and deliver? One option would be to just define another instance variable, but then we can't base methods off of that. So instead, we want to use inheritance to create a custom class with methods and variables that build upon the last one for a more specific usecase.

# Example

class dineInOrder(order):

# Now in my state, takeout and delivery orderss

# Don't have sales tax. Dine-in is the only one that does.

#

def __init__(self, orderID=None, food, complete=False, price, taxRate=0.07):

order.__init__(self,orderID, food, complete, price)

self.__tax = taxRate;

def finalPrice():

# Returns the actual price of the food, sales tax included.

return (self.__tax+1)*price

User Hyounis
by
5.5k points