70 likes | 82 Views
Understand Java interfaces to define method signatures for code reusability. Learn how to implement, cast, and work with interfaces effectively in Java programming. Practice implementing multiple interfaces and testing abstract classes and different employee types.
E N D
Interfaces • Generally, interface describes public members of a class • Java interface allows programmer to specify method signatures for reusability • An interface cannot be instantiated • A class that implements and interface must implement the methods defined in the interface • Example – sortable
Syntax public interface interface_name { //method signature public return_type name(params); } public class class_name implements interface_name { //method implementation public return_type name(params) { } }
Casting public class Cow implements Animal { public void speak() { System.out.println(“Moo”); } public void milk() { ... } } public interface Animal { public void speak(); } public class Bird implements Animal { public void speak() { System.out.println(“Squawk”); } public void fly() { ... } }
Casting Animal[] animals = new Animal[3]; animals[0] = new Cow(); animals[1] = new Bird(); animals[2] = new Cow(); //milk all cows for(int i = 0; i < animals.length; i++) { if(animals[i] instanceof Cow) { Cow c = (Cow)animals[i]; c.milk(); } }
Implementing Multiple Interfaces public class class_name implements interface1, interface2, interface3 { //implementation of ALL methods from interfaces 1, 2, and 3 } Example: interface Student with method listClasses interface ComputerScientist with method writeProgram class CSStudent implements Student and ComptuerScientist must implement methods listClasses and writeProgram
Exercises • Implement (and test!) an abstract class Employee and two classes that implement Employee. • You can choose the type of employees you want to implement • Change Sortable and SortedList such that you can keep a sorted list of your employees • You will need to modify Employee to implement your modified Sortable interface