Need help with this. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Need help with this.

Write a base class called Polygon that will have instance members width and height. Create a derived class from Polygon and call it Triangle. Triangle will have a method called areaT which will calculate area of triangle. Create another derived class called Rectangle which will have methods areaR (area of rectangle) and perimeterR (perimeter of rectangle). Create constructors and method definitions for each class. Finally create the main class and create objects of the classes to test the methods.

29th Nov 2017, 3:42 AM
Trever Young
Trever Young - avatar
7 Answers
+ 6
Java: public class Main { public static void main(String[] args) { Triangle t = new Triangle(5, 3); t.areaT(); Rectangle r = new Rectangle(2, 5); r.areaR(); r.perimeterR(); } } class Polygon { protected int width; protected int height; Polygon(int width, int height) { this. width = width; this.height = height; } } class Triangle extends Polygon { Triangle(int width, int height) { super(width, height); } void areaT() { System.out.println((width * height) / 2.0); } } class Rectangle extends Polygon { Rectangle(int width, int height) { super(width, height); } void areaR() { System.out.println(width * height); } void perimeterR() { System.out.println((width * 2) + (height * 2)); } }
29th Nov 2017, 4:05 AM
ChaoticDawg
ChaoticDawg - avatar
+ 6
C++ #include <iostream> using namespace std; class Polygon { protected: int width; int height; public: Polygon(int w, int h): width(w), height(h){} }; class Triangle: public Polygon { public: Triangle(int w, int h): Polygon(w, h) {} void areaT() { cout << (width * height) / 2.0 << endl; } }; class Rectangle: public Polygon { public: Rectangle(int w, int h): Polygon(w, h) {} void areaR() { cout << width * height << endl; } void perimeterR() { cout << (width * 2) + (height * 2) << endl; } }; int main() { Triangle t(5, 3); t.areaT(); Rectangle r(2, 5); r.areaR(); r.perimeterR(); return 0; }
29th Nov 2017, 4:30 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Is it in Java?
29th Nov 2017, 3:45 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
Please provide the language you're asking about in your post.
29th Nov 2017, 3:46 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Appologies for not stating that it was in c++
29th Nov 2017, 4:11 AM
Trever Young
Trever Young - avatar
+ 2
It's c++
29th Nov 2017, 4:07 AM
Trever Young
Trever Young - avatar
+ 1
Much appreciated
29th Nov 2017, 4:42 AM
Trever Young
Trever Young - avatar