Define a Pet class that stores the pet’s name, age, and weight. Add appropriate constructors, accessor, and mutator functions. Also define a function named getLifespan that returns a string with the value “unknown lifespan.” Next, define a Dog class that is derived from Pet. The Dog class should have a private member variable named breed that stores the breed of the dog. Add mutator and accessor functions for the breed variable and appropriate constructors. Redefine the getLifespan function to return "Approximately 7 years" if the dog’s weight is over 100 pounds and "Approximately 13 years" if the dog’s weight is under 100 pounds. Next, define a Rock class that is derived from Pet. Redefine the getLifespan function to return “Thousands of years”. Finally, write a test program that creates instances of pet rocks and pet dogs that exercise the inherited and redefined functions
时间: 2024-03-25 17:36:56 浏览: 53
dog.class
Sure, here is an implementation of the classes and the test program in Python:
```python
class Pet:
def __init__(self, name, age, weight):
self.name = name
self.age = age
self.weight = weight
def getName(self):
return self.name
def getAge(self):
return self.age
def getWeight(self):
return self.weight
def setName(self, name):
self.name = name
def setAge(self, age):
self.age = age
def setWeight(self, weight):
self.weight = weight
def getLifespan(self):
return "unknown lifespan"
class Dog(Pet):
def __init__(self, name, age, weight, breed):
super().__init__(name, age, weight)
self.breed = breed
def getBreed(self):
return self.breed
def setBreed(self, breed):
self.breed = breed
def getLifespan(self):
if self.weight > 100:
return "Approximately 7 years"
else:
return "Approximately 13 years"
class Rock(Pet):
def getLifespan(self):
return "Thousands of years"
# Test program
dog1 = Dog("Max", 3, 80, "Labrador")
dog2 = Dog("Buddy", 5, 120, "Great Dane")
rock1 = Rock("Rocky", 1000000, 1000000)
print(dog1.getName(), dog1.getLifespan()) # Output: Max Approximately 13 years
print(dog2.getName(), dog2.getLifespan()) # Output: Buddy Approximately 7 years
print(rock1.getName(), rock1.getLifespan()) # Output: Rocky Thousands of years
```
In this implementation, the `Pet` class defines the basic attributes and methods that all pets share. The `Dog` class is derived from `Pet` and adds a breed attribute, as well as a redefined `getLifespan` method that takes into account the dog's weight. The `Rock` class is also derived from `Pet` and has its own redefined `getLifespan` method that always returns "Thousands of years".
The test program creates instances of `Dog` and `Rock` and calls their respective methods to demonstrate the inheritance and redefinition of methods.
阅读全文