In: Computer Science
Question B Considering how objects list in their own memory space and can behave almost like independent entities, think about some possible programs that you could create with this concept. (for example, a simulated worlds). Be specific in your description as to how OOP concepts would be employed.
As programming language was not mentioned so provided the example in commonly asked language (C++).
Base class BaseShape.h===
#include <iostream>
// Base class
class BaseShape{
public: float area; //area Of the Shape
public: BaseShape(); //Constructor
public: float CalculateArea(); //Method to Calculate Area of the Shape
};
BaseShape.cpp=====
#include "BaseShape.h"
#include <iostream>
//default implementaion of Base class
BaseShape::BaseShape(){
area = 0;
}
float BaseShape::CalculateArea(){
return area;
};
Derived class Square.h===========
//dervied class This shows inheritance
class Square: public BaseShape {
public:
Square(float side);
float CalculateArea();
//new method used by dervied class which is not in base class
float CalculatePerimeter();
private:
float side; /*new variables this shows data hiding/abstraction as variable is private and can't be accessed outside*/
};
Square.cpp=====
#include "BaseShape.h"
#include "Square.h"
#include <iostream>
using namespace std;
Square::Square(float sideOfSquare){
side = sideOfSquare;
}
/*redefining the functionality of base class function in dervied class which shows Method Overridding of OOP */
float Square::CalculateArea(){
return side*side;
}
//Adding new functionality derived class
float Square::CalculatePerimeter(){
return 4*(side);
}
main program:======
#include "BaseShape.h"
#include "Square.h"
#include <iostream>
using namespace std;
int main() {
Square testSquare1(5);
Square testSquare2(12);
cout << "The area of the Square1 is " << testSquare1.CalculateArea() << '\n';
cout << "The perimeter of the Square1 is " << testSquare1.CalculatePerimeter() << '\n';
//This shows the data encapsulation with in the object, both the object have their own data
cout << "The area of the Square2 is " << testSquare2.CalculateArea() << '\n';
cout << "The perimeter of the Square2 is " << testSquare2.CalculatePerimeter() << '\n';
return 0;
}
output:
Please rate your answer.