Activity 10: Object-Oriented Programming OOP in TypeScript

Class and Object:

A class is a blueprint or a template that defines the properties and methods of an object. An object is an instance of a class, which has its own set of properties and methods.

Classes define the structure and behavior of objects, while objects have their own set of values and can be manipulated independently.

Classes are defined using the class keyword, followed by the name of the class. Properties and methods are defined within the class using the public, private, or protected access modifiers.

Example Code:

Encapsulation

Encapsulation is the concept of hiding the internal details of an object from the outside world, while exposing only the necessary information through public methods.

Encapsulation helps to reduce coupling between objects and makes it easier to modify or extend the internal implementation without affecting the external interface.

Access modifiers like public, private, and protected are used to control access to class properties and methods.

Example Code:

Inheritance

Inheritance is the concept of creating a new class that inherits the properties and methods of an existing class.

Inheritance allows for code reuse and facilitates the creation of a hierarchy of classes with similar properties and methods.

The extends keyword is used to inherit from a parent class.

Example Code:

Polymorphism

Polymorphism is the concept of having multiple forms or implementations of a method or property.

Polymorphism allows for more flexibility and dynamic behavior in code.

Method overriding (runtime polymorphism) and method overloading (compile-time polymorphism) are used to achieve polymorphism.

Example Code:

Abstraction

Abstraction is the concept of showing only the necessary information to the outside world while hiding the internal implementation details.

Abstraction helps to reduce complexity and make code more modular and reusable.

Abstract classes and interfaces are used to implement abstraction.

Example Code:

Additional OOP Concepts

  • Interfaces: Interfaces define the structure of an object without providing implementation details. They help in achieving abstraction.

  • Constructor Overloading: Constructor overloading allows multiple constructor definitions using optional parameters.

  • Getters and Setters: Getters and setters provide encapsulation for accessing properties.