Lesson 6 / 7

Classes and Access Modifiers

class Course {n    private title: string;n    public lessonCount: number;nn    constructor(title: string, lessonCount: number) {n        this.title = title;n        this.lessonCount = lessonCount;n    }nn    getTitle(): string {n        return this.title;n    }n}nnconst tsCourse = new Course("TypeScript", 7);nconsole.log(tsCourse.getTitle());

Access modifiers

private restricts a property to being accessed only from inside the class itself — tsCourse.title from outside would be a compile error. public is the default if you write nothing at all; being explicit about it is purely a readability choice. This mirrors exactly the same private/public distinction from the Java and C++ courses.

Shorthand constructor properties

class Course {n    constructor(n        private title: string,n        public lessonCount: numbern    ) {}nn    getTitle(): string {n        return this.title;n    }n}

Writing the access modifier directly on a constructor parameter is TypeScript-only shorthand — it declares the property AND assigns it from the matching argument in one line, instead of writing both a class field and a manual this.title = title; assignment separately.

Interfaces with classes

interface Playable {n    play(): void;n}nnclass VideoLesson implements Playable {n    play(): void {n        console.log("Playing video...");n    }n}

implements requires a class to provide every method an interface declares — the same contract idea from the Java course’s interfaces lesson, checked here at compile time rather than only surfacing as a runtime error.