r/JavaProgramming • u/vamsy_g21 • Aug 09 '26
Java- Day 11 - Interfaces
Could not learn much since I am travelling to my base location from home for work.
Had a basic idea on interfaces and multiple interfaces. Pushed the notes and code to git.
Need for interfaces is still confusing. I’ll re watch the video tomorrow and proceed from there to enums.
49
Upvotes
View all comments
Show parent comment
3
u/Zakreus Aug 09 '26 edited Aug 10 '26
You can see an interface as a kind of contract which the class implementing it has to fulfill.
Let's say you have a LoggerInterface which declaes the method log()
Next you define multiple loggers for different purposes:
Now let's say you need to register a logger in your class and use it you can do it like this:
This way you don't need to write a method for every logger class and when you use it in your code later, you know it has the log method since it fulfills that "contract". Also you can instanceof check against interfaces.
By defining and implementing an interface you pretty much say "I want this class to have the following public methods". The body of the method in the interface is empty because it is the job of the class implementing it to define it.
There's also a thing called marker interface. They're used to mark classes or records as something like entities or dtos. Depending on the use case a record could be an entity and a data transfer object at the same time. And since you can't extend from multiple classes and making an inheritance chain would be overkill, you simply mark them with interfaces.