I have two questions
Why do we need interface in java even if abstract class can do the functionality of interfaces?
On searching i found a place where abstract class fails to do the functionality of interfaces,
that is when a class needs to implement multiple interfaces.
Is it the only reason for bringing up the interfaces concept in java?
What is the use of static final variables in interfaces? Need example programs that state usage of variables in interfaces are welcome.
Thanks in Advance.
Like you said, you can only inherit from one abstract class, but many interfaces. Also, inheriting implies "is-a" relationship, but an interface specifies some set of operations an object must support -- essentially it's behavior. I see these as separate ideas. In my experience, classes tend to be nouns (e.g. Integer
, List
) and interfaces are verbs (e.g. Cloneable
, Serializable
).
If a class implements an interface with constants, then the class can refer to those constants without a qualifying class name (javapractices.com). However, as this post explains, it is a bad practice.
Interfaces are useful in these contexts:
1-> As you mentioned , In Java we can extend only one Class but can implement multiple interfaces.And this is really implement for example if you want to create a background Thread in your Class and your extending some Class for reusability,then how ill you extend Thread Class? In this case Runnable comes to rescue which is an interface.
2->Also interfaced help us to enforce a certain design pattern.
3->Also serve as markable interfaces as in case of Serializable Interface
Variables in interface are static variables that act as gloabal and can be shared with all Classes that implement that interface
Why do we need interface in java even if abstract class can do the functionality of interfaces? On searching i found a place where abstract class fails to do the functionality of interfaces, that is when a class needs to implement multiple interfaces. Is it the only reason for bringing up the interfaces concept in java?
Java doesn't support multiple class inheritance. So you can implement multiple inteface. more importantly you can implement interface and extend other class at the same time. If you used abstract class in place of interface which would not be possible.
What is the use of variables in interfaces? Need example programs that state usage of variables in interfaces are welcome.
Any "field" you declare in an interface will be a public static final field. In other words, a constant. So if you want to use any constant in all the subclass then you can define those in interface
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With