YouTip LogoYouTip

Ts Class

Classes are a core concept of Object-Oriented Programming (OOP). They act as a template or blueprint for creating objects with the same properties and methods. TypeScript fully supports OOP, offering features like classes, inheritance, and access modifiers. Classes encapsulate data (properties) and behavior (methods), making code more modular, reusable, and maintainable. Through classes, we can create multiple objects with the same structure; these objects are called instances of the class. * * * ## Class Definition TypeScript uses the `class` keyword to define a class. A class can contain the following members: * **Fields**: Variables declared in a class, representing the properties of an object. * **Constructor**: A special method called when a class is instantiated, used to initialize the object. * **Method**: Functions defined in a class, representing the behavior of an object. ### Syntax class class_name { // Field declarations field1: type; field2: type; // Constructor constructor(parameters) { // Initialization code } // Method methodName(): return_type { // Method implementation }} ### Example: Creating a Simple Class ## Example // Define an empty Person class class Person { } **Compiled JavaScript:** ## Example var Person =/** @class */(function(){ function Person(){ } return Person; }()); * * * ## Class Fields and Constructor Class fields are where object data is stored. The constructor is automatically called when an object is created to initialize the fields. ## Example // Define the Car class class Car { // Field: Describes the car's properties engine: string; // Constructor: Initializes engine when creating an object constructor(engine: string) { this.engine = engine; } // Method: Displays engine information disp(): void { console.log("Engine model: " + this.engine); } } // Create an instance of the class var car = new Car("V8 Engine"); // Access the field console.log("Reading engine: " + car.engine); // Call the method car.disp(); **Output:** Reading engine: V8 EngineEngine model: V8 Engine **Explanation:** * The `this` keyword refers to the current instance of the class. * Constructor parameter names can be the same as field names; use `this.field` to distinguish them. * Use the `new` keyword to create an instance of a class. > **Note:** TypeScript classes are compiled into JavaScript's constructor function prototype pattern. Interfaces do not appear in the compiled output. * * * ## Access Control Modifiers TypeScript provides three access modifiers to control the accessibility of class members: | Modifier | Description | | --- | --- | | `public` | Public members, accessible from anywhere (default) | | `private` | Private members, accessible only within the class | | `protected` | Protected members, accessible within the class and its subclasses | ### public (Default) ## Example class Person { public name: string; // Public property public age: number; // Public property constructor(name: string, age: number) { this.name = name; this.age = age; } public introduce(): void { console.log("I am " + this.name + ", " + this.age + " years old"); } } var person = new Person("Alice", 25); console.log("Name: " + person.name); // Accessible person.introduce(); // Accessible ### private (Private) ## Example class Person { public name: string; private secret: string; // Private property, not directly accessible from outside constructor(name: string, secret: string) { this.name = name; this.secret = secret; } // Public method can access private property public revealSecret(): void { console.log("Secret: " + this.secret); } } var person = new Person("Alice", "I love programming"); console.log("Name: " + person.name); // Accessible // console.log(person.secret); // Error: 'secret' is a private property person.revealSecret(); // Access private property via public method ### protected (Protected) ## Example class Person { protected name: string; // Protected property constructor(name: string) { this.name = name; } protected sayHello(): void { console.log("Hello, I am " + this.name); } } class Student extends Person { private grade: string; constructor(name: string, grade: string) { super(name); this.grade = grade; } public introduce(): void { // Subclass can access protected properties and methods console.log("I am " + this.name + ", grade: " + this.grade); this.sayHello(); } } var student = new Student("Bob", "Senior Year"); student.introduce(); // Accessible // console.log(student.name); // Error: 'name' is a protected property **Output:** I am Bob, grade: Senior YearHello, I am Bob * * * ## Class Inheritance Inheritance allows creating a class (subclass) that acquires properties and methods from another class (superclass). The subclass can reuse the superclass's code and can also extend or override the superclass's behavior. ### Basic Syntax class child_class extends parent_class { // New properties and methods in the subclass} ### Single Inheritance ## Example // Superclass: Shape class Shape { area: number; constructor(a: number) { this.area = a; } } // Subclass: Circle, inherits from Shape class Circle extends Shape { disp(): void { console.log("Circle area: " + this.area); } } var circle = new Circle(223); circle.disp(); **Output:** Circle area: 223 ### Multiple Inheritance TypeScript does not support multiple inheritance (a class inheriting from multiple classes), but it does support multilevel inheritance (A inherits from B, B inherits from C): ## Example // Root class class Root { str: string; } // Child class: Inherits from Root class Child extends Root { } // Leaf class: Inherits from Child (Multilevel inheritance) class Leaf extends Child { } var leaf = new Leaf(); leaf.str = "hello"; console.log("str value: " + leaf.str); **Output:** str value: hello * * * ## Method Overriding Subclasses can override methods of the superclass, meaning they define a method with the same name as in the superclass to implement their own behavior. Use the `super` keyword to call the superclass's method. ## Example // Superclass class PrinterClass { doPrint(): void { console.log("Superclass doPrint() method"); } } // Subclass: Overrides superclass method class StringPrinter extends PrinterClass { doPrint(): void { // Call the superclass's method super.doPrint(); // Subclass's own logic console.log("Subclass doPrint() method"); } } var obj = new StringPrinter(); obj.doPrint(); **Output:** Superclass doPrint() methodSubclass doPrint() method * * * ## Static Members Members defined with the `static` keyword belong to the class itself, not to instances of the class. They can be accessed directly via the class name without creating an instance. ## Example class StaticMem { // Static property static num: number; // Static method static disp(): void { console.log("num value is " + StaticMem.num); } } // Access static members directly via class name StaticMem.num = 12; StaticMem.disp(); **Output:** num value is 12 > **Use Case:** Static members are often used to define class constants, utility methods, or the singleton pattern. * * * ## instanceof Operator `instanceof` is used to determine if an object is an instance of a particular class. ## Example class Person { } var obj = new Person(); var isPerson = obj instanceof Person; console.log("Is obj an instance of Person? " + isPerson); **Output:** Is obj an instance of Person? true * * * ## Class Implementing an Interface A class can use the `implements` keyword to implement an interface, ensuring the class adheres to the contract defined by the interface. ## Example // Define an interface interface ILoan { interest: number; // Interest rate } // Class implements the interface class AgriLoan implements ILoan { interest: number; rebate: number; // Rebate constructor(interest: number, rebate: number) { this.interest = interest; this.rebate = rebate; } } var loan = new AgriLoan(10, 1); console.log("Interest rate: " + loan.interest + "%, Rebate: " + loan.rebate); **Output:** Interest rate: 10%, Rebate: 1 * * * ## Abstract Classes Abstract classes cannot be instantiated and can only serve as base classes for inheritance by subclasses. Abstract classes can contain abstract methods (placeholder methods without implementation), which subclasses must implement. ## Example // Abstract class abstract class Animal { abstract makeSound(): void; // Abstract method, must be implemented by subclasses move(): void { console.log("Animal is moving"); } } // Concrete class: Inherits from abstract class class Dog extends Animal { makeSound(): void { console.log("Woof woof!"); } } var dog = new Dog(); dog.move(); dog.makeSound(); **Output:** Animal is movingWoof woof! * * * ## Comprehensive Example Comprehensive application of various class features: ## Example // Interface definition interface I Printable { print(): void; } // Abstract class abstract class Item { protected name: string; protected price: number; constructor(name: string, price: number) { this.name = name; this.price = price; } abstract getDetails(): string; } // Concrete class class Product extends Item implements I Printable { private category: string; constructor(name: string, price: number, category: string) { super(name, price); this.category = category; } // Implement abstract method getDetails(): string { return `Product: ${this.name}, Price: Β₯${this.price}, Category: ${this.category}`; } // Implement interface method print(): void { console.log(this.getDetails()); } // Static method static create(name: string, price: number): Product { return new Product(name, price, "Default Category"); } } // Usage var product = Product.create("Laptop", 5999); product.print(); // Discount method class DiscountedProduct extends Product { private discount: number; constructor(name: string, price: number, category: string, discount: number) { super(name, price, category); this.discount = discount; } getDetails(): string { var discountedPrice = this.price * (1 - this.discount / 100); return `Product: ${this.name}, Original Price: Β₯${this.price}, Discount: ${this.discount}%, Current Price: Β₯${discountedPrice.toFixed(2)}`; } } var discountedProduct = new DiscountedProduct("Smartphone", 2999, "Electronics", 20); discountedProduct.print(); **Output:** Product: Laptop, Price: Β₯5999, Category: Default CategoryProduct: Smartphone, Original Price: Β₯2999, Discount: 20%, Current Price: Β₯2399.20 * * * ## Summary TypeScript classes provide complete support for object-oriented programming: * **Class Definition**: Use the `class` keyword, containing fields, constructors, and methods. * **Access Modifiers**: `public`, `private`, `protected` control member access permissions. * **Inheritance**: Use `extends` to implement class inheritance, supporting multilevel inheritance. * **Method Overriding**: Subclasses can override superclass methods, using `super` to call the superclass. * **Static Members**: Use the `static` keyword; they belong to the class itself, not instances. * **Interface Implementation**: Use the `implements` keyword to implement interfaces. * **Abstract Classes**: Use the `abstract` keyword; they cannot be instantiated and serve as base classes. Classes are the foundation of object-oriented programming in TypeScript. Using classes appropriately makes code more structured and maintainable.
← Ts NamespaceTs Array β†’