Theo's Typesafe CultTTC
Theo's Typesafe Cult4y ago
72 replies
nexxel

Need help in OOP

class Shape {
  radius: number;
  length: number;
  breadth: number;
  base: number;
  height: number;

  constructor(radius: number) {
    this.radius = radius;
    this.length = 0;
    this.breadth = 0;
    this.base = 0;
    this.height = 0;
  }
}

class Circle extends Shape {
  constructor(radius: number) {
    super(radius);
  }

  getArea(): number {
    return Math.PI * this.radius * this.radius;
  }
}

class Rectangle extends Shape {
  constructor(length: number, breadth: number) {
    super(0);
    this.length = length;
    this.breadth = breadth;
  }

  getArea(): number {
    return this.length * this.breadth;
  }
}

class Triangle extends Shape {
  constructor(base: number, height: number) {
    super(0);
    this.base = base;
    this.height = height;
  }

  getArea(): number {
    return (this.base * this.height) / 2;
  }
}

const circle = new Circle(10);
const radius = new Rectangle(3, 4);
const triangle = new Triangle(5, 6);

console.log(circle.getArea());
console.log(radius.getArea());
console.log(triangle.getArea());


is there a better way to do this using OOP? this feels a bit inconsistent to me but im inexperienced in OOP and don't know if there's a better way to do this. would love some help!
Was this page helpful?