Core Java Interview Questions and Answers
Ques. When should I use abstract methods?Ans. Abstract methods are usually declared where two or more subclasses are expected to fulfil a similar role in different ways. Often the subclasses are required to the fulfil an interface, so the abstract superclass might provide several of the interface methods, but leave the subclasses to implement their own variations of the abstract methods. Abstract classes can be thought of as part-complete templates that make it easier to write a series of subclasses.
For example, if you were developing an application for working with different types of documents, you might have a Document interface that each document must fulfil. You might then create an AbstractDocument that provides concrete openFile() and closeFile() methods, but declares an abstract displayDocument(JPanel) method. Then separate LetterDocument, StatementDocument or InvoiceDocument types would only have to implement their own version of displayDocument(JPanel) to fulfil the Document interface.
Is it helpful? Yes No
Most helpful rated by users:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- When should I use abstract methods?