Question

In: Computer Science

Inheritance - Polymorphism One advantage of using subclasses is the ability to use polymorphism. The idea...

Inheritance - Polymorphism

One advantage of using subclasses is the ability to use polymorphism.

The idea behind polymorphism is that several different types of objects can have the same methods, and be treated in the same way.

For example, have a look at the code we’ve included for this problem. We’ve defined Shape as an abstract base class. It doesn’t provide any functionality by itself, but it does supply an interface (in the form of .area() and .vertices() methods) which are meaningful for any type of 2D Shape.

The total_area function makes use of this to calculate the area of any kind of Shape. We’ve provided an example of this with two Square instances.

We want you to write RightAngledTriangle and Rectangle classes which implement this interface.

The constructor for RightAngledTriangle accepts one argument, vertices, being a list of the points of the triangle relative to its origin. The first vertex will be at the right angle.

The constructor for Rectangle accepts width and height.

class Shape():
"""
A representation of a shape.

"""
def __init__(self, origin=(0, 0)):
"""Construct a shape object
  
Parameters:
origin(tuple<int, int>): origin of the shape
  
"""

self.origin = origin

def area(self):
"""
(int) Return the area of the shape.

"""
raise NotImplementedError()

def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.
  
"""
raise NotImplementedError()


class Square(Shape):
"""A Square object"""
def __init__(self, side_length, origin=(0, 0)):
"""
Construct a square object
  
Parameters:
side_length (int): Length of the sides of the square
origin (tuple<int, int>): Coordinate of topleft corner of square
  
"""
super().__init__(origin=origin)

self.side_length = side_length

def area(self):
"""
(int) Return the area of the shape.
  
"""
return self.side_length * self.side_length

def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.
  
"""
x, y = self.origin

return [
(x, y),
(x, y + self.side_length),
(x + self.side_length, y + self.side_length),
(x + self.side_length, y),
]


def total_area(shapes):
"""
Return the total area of the given list of shapes.

Parameters:
shapes (list<Shape>): The list of shapes to sum the area for.

Return:
int: The total area of the list of shapes, being the sum of the area of
each individual shape.

"""
area = 0.

for shape in shapes:
area += shape.area()

return area


def outer_bounds(shapes):
"""
Return the outer bounds of the given list of shapes.

Parameters:
shapes (list<Shape>): The list of shapes to return the outer bounds for.

Return:
tuple<tuple<int, int>, tuple<int, int>>:

The first element of the tuple is the top-left corner of a rectangle
which could enclose every shape in the given list.
The second element of the tuple is the bottom-right corner of that same
rectangle.

The top-left corner of the rectangle will be, at minimum, (0, 0).

"""
vertices = []

for shape in shapes:
for vertex in shape.vertices():
vertices.append(vertex)

top_left_x = 0
top_left_y = 0
bottom_right_x = 0
bottom_right_y = 0

for x, y in vertices:
if x < top_left_x:
top_left_x = x
elif x > bottom_right_x:
bottom_right_x = x

if y < top_left_y:
top_left_y = y
elif y > bottom_right_y:
bottom_right_y = y

return (top_left_x, top_left_y), (bottom_right_x, bottom_right_y)


# example usage
# note that total_area doesn't know nor care that we used instances of Square
shapes = [Square(2), Square(4, origin=(2, 2))]
area = total_area(shapes)

Solutions

Expert Solution

class Shape():
"""
A representation of a shape.

"""


def __init__(self, origin=(0, 0)):
"""Construct a shape object

Parameters:
origin(tuple<int, int>): origin of the shape

"""


self.origin = origin


def area(self):
"""
(int) Return the area of the shape.

"""


raise NotImplementedError()


def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.

"""


raise NotImplementedError()


class Square(Shape):
"""A Square object"""


def __init__(self, side_length, origin=(0, 0)):
"""
Construct a square object

Parameters:
side_length (int): Length of the sides of the square
origin (tuple<int, int>): Coordinate of topleft corner of square

"""


super().__init__(origin=origin)

self.side_length = side_length


def area(self):
"""
(int) Return the area of the shape.

"""


return self.side_length * self.side_length


def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.

"""


x, y = self.origin

return [
(x, y),
(x, y + self.side_length),
(x + self.side_length, y + self.side_length),
(x + self.side_length, y),
]

class Rectangle(Shape):
"""A Rectangle object"""


def __init__(self, width, height, origin=(0, 0)):
"""
Construct a rectangle object

Parameters:
width (int): Width of the rectangle
height (int): Height of the rectangle
origin (tuple<int, int>): Coordinate of topleft corner of rectangle

"""


super().__init__(origin=origin)

self.width = width
self.height = height


def area(self):
"""
(int) Return the area of the shape.

"""


return self.width * self.height


def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.

"""


x, y = self.origin

return [
(x, y),
(x, y + self.height),
(x + self.width, y + self.height),
(x + self.width, y),
]

class RightAngledTriangle(Shape):
"""A RightAngledTriangle object"""


def __init__(self, vertices, origin=(0, 0)):
"""
Construct a right angled triangle object

Parameters:
vertices list<tuple<int, int>>: Length of the sides of the square
origin (tuple<int, int>): Coordinate of topleft corner of square

"""


super().__init__(origin=origin)

self.vertices = vertices


def area(self):
"""
(int) Return the area of the shape.

"""

return (abs(self.vertices[0][0] + self.vertices[0][1] - self.vertices[1][0] - self.vertices[1][1]) *
abs(self.vertices[0][0] + self.vertices[0][1] - self.vertices[2][0] - self.vertices[2][1]))/2


def vertices(self):
"""
Return the vertices of the shape.

Return:
list<tuple<int, int>>: The vertices of the shape, as a list of tuples
representing two dimensional points.
This list may be returned in any order.

"""

return self.vertices

def total_area(shapes):
"""
Return the total area of the given list of shapes.

Parameters:
shapes (list<Shape>): The list of shapes to sum the area for.

Return:
int: The total area of the list of shapes, being the sum of the area of
each individual shape.

"""


area = 0.

for shape in shapes:
area += shape.area()

return area


def outer_bounds(shapes):
"""
Return the outer bounds of the given list of shapes.

Parameters:
shapes (list<Shape>): The list of shapes to return the outer bounds for.

Return:
tuple<tuple<int, int>, tuple<int, int>>:

The first element of the tuple is the top-left corner of a rectangle
which could enclose every shape in the given list.
The second element of the tuple is the bottom-right corner of that same
rectangle.

The top-left corner of the rectangle will be, at minimum, (0, 0).

"""


vertices = []

for shape in shapes:
for vertex in shape.vertices():
vertices.append(vertex)

top_left_x = 0
top_left_y = 0
bottom_right_x = 0
bottom_right_y = 0

for x, y in vertices:
if x < top_left_x:
top_left_x = x
elif x > bottom_right_x:
bottom_right_x = x

if y < top_left_y:
top_left_y = y
elif y > bottom_right_y:
bottom_right_y = y

return (top_left_x, top_left_y), (bottom_right_x, bottom_right_y)

# example usage
# note that total_area doesn't know nor care that we used instances of Square
shapes = [Square(2), Square(4, origin=(2, 2)), Rectangle(2, 3), Rectangle(4, 3, origin=(3, 3)),
RightAngledTriangle([(0, 0), (2, 0), (0, 2)])]
area = total_area(shapes)
print('Total area:', area)


Related Solutions

This question demonstrates the use of inheritance and polymorphism. Design a Ship class that has the...
This question demonstrates the use of inheritance and polymorphism. Design a Ship class that has the following members: • A field for the name of the ship (a string). • A field for the year that the ship was built (a string). • A constructor and appropriate accessors and mutators. • A toString method that overrides the toString method in the Object class. The Ship class toString method should display the ship’s name and the year it was built. Design...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface...
This is for a java program. Payroll System Using Inheritance and Polymorphism 1. Implement an interface called EmployeeInfo with the following constant variables: FACULTY_MONTHLY_SALARY = 6000.00 STAFF_MONTHLY_HOURS_WORKED = 160 2. Implement an abstract class Employee with the following requirements: Attributes last name (String) first name (String) ID number (String) Sex - M or F Birth date - Use the Calendar Java class to create a date object Default argument constructor and argument constructors. Public methods toString - returning a string...
The purpose of this lab is to practice using inheritance and polymorphism. We need a set of classes for an Insurance company.
The purpose of this lab is to practice using inheritance and polymorphism.    We need a set of classes for an Insurance company.   Insurance companies offer many different types of policies: car, homeowners, flood, earthquake, health, etc.    Insurance policies have a lot of data and behavior in common.   But they also have differences.   You want to build each insurance policy class so that you can reuse as much code as possible.   Avoid duplicating code.   You’ll save time, have less code to...
Write a simple short Java program of your choice which illustrates inheritance, polymorphism and the use...
Write a simple short Java program of your choice which illustrates inheritance, polymorphism and the use of interfaces. The program should not take up more than half a page of size A4.
Using ONE of the following themes to create a class and demonstrate the idea. Use this...
Using ONE of the following themes to create a class and demonstrate the idea. Use this to create a solution (two ADTs and a driver program) to demonstrate the following concepts. Create a one page summary to describe where you are using each of these concepts. Themes:(PICK ONE) a house has a door a semester has a holiday break a cell phone has a shatterproof case a chair has a cushion Concepts to include: composition separating interface from implementation an...
Polymorphism and Inheritance Shape.h class Shape {             string color;             bool filled; public:      &n
Polymorphism and Inheritance Shape.h class Shape {             string color;             bool filled; public:             Shape();             Shape(string, bool);             string getColor();             bool isFilled();             void setColor(string);             void setFilled(bool);             string toString(); //virtual string toString(); }; Rectangle.h class Rectangle : public Shape {             double length;             double width; public:             Rectangle();             Rectangle(double, double);             Rectangle(double, double, string, bool);             double getLength();             double getWidth();             void setLength(double);             void setWidth(double);             double getArea();             double getPerimeter();...
Question: In the context of EER data modeling, one can represent entities using superclasses and subclasses....
Question: In the context of EER data modeling, one can represent entities using superclasses and subclasses. I. Using your own model, explain why one would want to introduce the concepts of superclasses and subclasses into an EER model? CR[10 Marks ] II. Describe and illustrate using the model in question (I) the process of attribute inheritance. EV[5 Marks] III. With the model in question (I) describe and contrast the process of specialization with the process of generalization. CR[5 Marks ]...
Which Feature of OOP illustrates code reusability? Abstraction, Encapsulation, Inheritance, Polymorphism or All of them.
Which Feature of OOP illustrates code reusability? Abstraction, Encapsulation, Inheritance, Polymorphism or All of them.
Which one of the following is NOT an advantage of using ROE as a goal? A....
Which one of the following is NOT an advantage of using ROE as a goal? A. ROE is highly correlated with shareholder wealth maximisation. B. ROE and the DuPont analysis allow management to break down the performance and identify areas of strengths and weaknesses. C. ROE does not consider risk. D. All of the above are advantages of using ROE as a goal.
Give one advantage and one disadvantage of using a plasma excitation source (as oppaosed to a...
Give one advantage and one disadvantage of using a plasma excitation source (as oppaosed to a flame) for emission spectroscopy.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT