Interfaces
- Allows definition of classes’ structure
- final fields
- method names
- return data type
- Interfaces provides definition for creating classes
- Allows for polymorphism due to similarities
- While <ArrayList> might be declared & used in the main logic,
- helper classes can use Collection<T> so that other data types can be fed to it
- such as
- HashMap, Array, Enum
- Interfaces DON'T have constructors
- good for modeling behavior
- NOT for managing data
Code:
This method only accept ArrayLists (part of Collection data type I/F)
public void getOil(ArrayList<Olive> olives) {}
This is more flexible and can take any Data Type that implements the Collection I/F
public void getOil(Collection<Olive> olives) {
Creating Interfaces
- No constructor methods or other class elements
- Modeling behavior, not dynamic managment of data
- MUST BE PUBLIC OR ABSTRACT
- Only include the METHOD SIGNATURE
package com.lynda.olivepress.press;
public interface Press {
}
Creating a class with interface
Code:
package com.lynda.olivepress.press;
import java.util.Collection;
import com.lynda.olivepress.olives.Olive;
public class OlivePress2 implements Press {
@Override
public void getOil(Collection<Olive> olives) {
// TODO Auto-generated method stub
}
@Override
public int getTotalOil() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setTotalOil(int totalOil) {
// TODO Auto-generated method stub
}
}
- Log in to post comments