+ 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.
7 Respostas
+ 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));
}
}
+ 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;
}
+ 3
Is it in Java?
+ 3
Please provide the language you're asking about in your post.
+ 3
Appologies for not stating that it was in c++
+ 2
It's c++
+ 1
Much appreciated