Class 1, Part 2 |
Intro to Java 30-IT-396 |
|
Interfaces
-
Interfaces are like templates for classes.
-
They define the methods and constants, but they do not implement them.
-
Interfaces are not classes themselves, they are simply definitions of what
an inheriting class must contain.
-
You can only extend one class, but you can implement one
or more interfaces.
-
What's the difference?
-
Extending a class means you are inheriting the behavior of that
parent class.
-
Implementing an interface simply means you agree to implement the methods
of the interface.
-
Multiple inheritance is not permitted in Java. Multiple inheritance
is where you can extend more than one class, but this presents a problem.
What if you extend two classes that happen to have the same method
name? Which one does your subclass actually use?
-
Well, that is why Java does not permit multiple inheritance. But
that's also where interfaces come in - since they don't actually implement
any methods, two interfaces can have the same method name and not conflict.
Granted, if this does happen, it is generally a sign of poor design or
programming.
-
All methods of an interface are public. You do not need to specify
public when you write the method definitions in an interface, it is just
assumed. But, in your implementation, you must specify the public
modifier or the compiler will complain.
-
Interfaces cannot...
-
Contain instance fields. This would bring us to the multiple inheritance
problem.
-
Implement methods. See the discussion above.
-
So what's the use?
-
Polymorphism applies to interfaces.
-
For a class to implement an interface, you simply need to add 'implements
interfaceName'
after the class definition.
-
Example: public class Stock { is now public class Stock implements
Securities {
-
Example: Implementing the Comparable interface.
Interface Properties



Created by: Brandan
Jones January 4, 2002