Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Suppose you have developed an interface called


Download 1.52 Mb.
Pdf ko'rish
bet115/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   111   112   113   114   115   116   117   118   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Suppose you have developed an interface called
FileWriter as part of an API. It has a writeToCsv file
method that writes the contents passed in to a CSV file.
The API is implemented by different applications that
provide an implementation for the FileWriter interface.
Now, suppose you are required to add a new method to
the interface called writeToExcel which writes the
contents passed in to an excel file. How can you go about
with this change with minimal impact to the users of your
API?
Answer:
In the scenario described above, it is required to add a new
method to the FileWriter interface. Simply adding the method
to the interface will cause compilation errors in all the existing
classes that implement the interface and will require all the
classes to provide an implementation for the writeToExcel()
method. The best way to go about this is to add the
writeToExcel() method as a default method in the
FileWriter interface. Default methods are a new feature
added by Java 8. They allow you to create methods with method
bodies in an interface. Classes that implement the interface, do
not need to provide an implementation for default methods. So,
adding the writeToExcel() method as a default method in the
FileWriter interface will not impact the classes that implement


FileWriter. Default methods are added by Java 8. So, if you
are using an earlier Java version, then this solution would not
work. In that case, you can create a new version of the
FileWriter interface (say FileWriterEnhanced) that
extends the current FileWriter and add the
writeToExcel() method in the FileWriterEnhanced
interface. In this case, the existing code that implements the
FileWriter interface will work as it is. Any code that needs the
writeToExcel() method will need to implement the
FileWriterEnhanced interface.




Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   111   112   113   114   115   116   117   118   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling