Interfaces, Polymorphism and Packages
April 13th, 2016
Lecture Code
Key Points
- public interface iName
- public class className implements iName
- In an interface, you can declare constants and then abstract methods
- Polymorphism occurs when one method behaves differently when called
in the context of different class instances
Interfaces
- Interfaces provide a regimented list of methods that a certain
class is obligated to provide. A class is obligated to provide
them if it "implements" the interface.
- Think of an interface as a contract. If a class implements the
interface, it is contractually bound to provide the methods
listed in the interface.
- Interfaces enable teams of coders to work on two different
sections of code, knowing that because the interface is agreed
upon, their code will be compatible.
- link
Polymorphism
- Late binding: Resolving a specific method call on an object is
done at runtime instead of compile time.
- Polymorphism: Allowing multiple implementations of the same
method, where the specific method executed is chosen at runtime
based on the actual object. link
Packages
- Packages are ways to divide and organize classes into logical
groups.
- Packages are groups of classes that work together to
accomplish a common task (further supports encapsulation).
- Packages make it easier to find and use classes as well as
control access. link
Class Exercise
Declare an interface named iShape that has a method called getArea()
that returns a double. Declare and demonstrate a Circle class that
implements iShape. Declare and demonstrate a Square class that
implements iShape.