Object-Oriented Design
- Focuses on designing classes and objects in Java programming.
Interfaces
- A Java interface is a collection of abstract methods and constants.
- Methods in an interface:
- An abstract method has no body.
- All methods are public by default.
- Cannot be instantiated, only implemented.
- A class implements an interface by:
- Stating it in the class header.
- Defining all abstract methods.
- Example:
public interface Doable {
void doThis();
int doThat();
void doThis2(double value, char ch);
boolean doTheOther(int num);
}
Implementation Example
- Class implementing an interface example:
public class CanDo implements Doable {
public void doThis() { /* implementation */ }
public int doThat() { /* implementation */ }
// other methods
}
- A class can implement multiple interfaces.
Common Interfaces in Java
- Comparable:
- Contains the abstract method compareTo for object comparison.
- Can return negative, zero, or positive values.
- Iterator:
- Provides methods: hasNext, next, and remove for iterating collections.
- Iterable:
- Has a method iterator to return an Iterator object.
Enumerated Types
- Define a new data type with a list of possible values.
- Example:
enum Season { winter, spring, summer, fall }
- Can have methods and additional properties:
public enum Season {
winter("Dec-Feb"), spring("Mar-May");
private String span;
Season(String months) { this.span = months; }
public String getSpan() { return span; }
}
- Every enumerated type has a static method values that lists all values for that type, usable in loops.
Summary
- Interfaces and enumerated types are fundamental to object-oriented design in Java, allowing for well-structured code and type safety.