Interface in Java:
" Thank you, this helped a lot. I just have one question: do you have to declare the methods inside the interface as public, or are they public by default? Again, thank you for helping me understand this topic. "
The interface created in the video used an abstract method which was defined by its unique signature (method name, access modifiers, return type, parameters, etc.). While in the video we added in the modifier “public” to our display method to ensure that the method would be accessible by all other classes, technically this modifier can be omitted, since all method declarations in an interface are implicitly public. While some style guides advise against using the public modifier in these cases as it unnecessarily adds extra information and can draw attention away from more important lines of code, the most important thing is to be consistent throughout your code on how you define these methods. It’s also important to note that with interfaces that contain nothing but abstract method definitions, you would have to implement all those methods in your own class. You can’t pick and choose the methods you need".
|
What is an interface?
Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default. What is the "use" of interface ?
Interfaces are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class. |