InterviewSolution
| 1. |
What are abstract classes? When should you use one? |
|
Answer» Abstract classes are similar to interfaces in that they specify a contract for the objects, and you cannot instantiate them directly. HOWEVER, unlike interfaces, an abstract class may provide implementation details for one or more of its members. An abstract class marks one or more of its members as abstract. Any classes that EXTEND an abstract class have to provide an implementation for the abstract members of the superclass. Here is an example of an abstract class WRITER with two member functions. The write() method is marked as abstract, whereas the greet() method has an implementation. Both the FictionWriter and RomanceWriter classes that extend from Writer have to provide their specific implementation for the write method. abstract class Writer {abstract write(): void;greet(): void { console.log("Hello, there. I am a writer.");}}class FictionWriter EXTENDS Writer {write(): void { console.log("WRITING a fiction.");}}class RomanceWriter extends Writer {write(): void { console.log("Writing a romance novel.");}}const john = new FictionWriter();john.greet(); // "Hello, there. I am a writer."john.write(); // "Writing a fiction."const mary = new RomanceWriter();mary.greet(); // "Hello, there. I am a writer."mary.write(); // "Writing a romance novel." |
|