Challenge your knowledge of object-oriented principles and class syntax in TypeScript with this quiz covering inheritance, access modifiers, interfaces, and more. Strengthen your understanding of how TypeScript adds type safety and structure to classic object-oriented programming concepts.
In TypeScript, which keyword is used to create a new instance of a class named Animal, as shown in 'class Animal {}'?
Explanation: The correct way to instantiate a class in TypeScript is by using the 'new' keyword followed by the class name and parentheses, making 'new Animal()' the valid option. 'create Animal()' and 'instantiate Animal()' are not valid TypeScript syntax. 'Animal.new()' is also incorrect, as 'new' is not a method of the class but a keyword used to create new objects.
Which syntax correctly makes a class Dog inherit from another class Animal in TypeScript?
Explanation: 'class Dog extends Animal {}' properly uses the 'extends' keyword to establish inheritance from Animal to Dog. 'implements' is used for interfaces, not class inheritance. 'inherits' and the colon syntax ':', as in other languages, are not valid in TypeScript for inheritance.
Given 'class Person { private name: string; public age: number; }', which property can be accessed directly from outside an instance?
Explanation: 'age' is declared as public, so it can be accessed directly from outside the class instance. 'name' is private and cannot be accessed outside of the class. 'private' is a modifier, not a property, and 'Person' is the class itself, not a property. Only public properties are accessible from outside the class.
Which statement best describes a key difference between interfaces and abstract classes in TypeScript?
Explanation: Interfaces in TypeScript only define the shape and signatures of members and cannot provide any actual code; abstract classes, however, can contain implementations for some methods. Interfaces do not have private members, while 'abstract classes cannot define any methods' is incorrect since they can. Interfaces are created with the 'interface' keyword, not 'class'.
How is a static method defined and called in a TypeScript class named Calculator?
Explanation: Static methods are defined with the 'static' keyword and called on the class itself, such as 'Calculator.add(2, 3)'. The second and third options have invalid syntax and use of 'static'. The last option uses the 'new' keyword and instance method call, which is incorrect for static members.