5.2 Abstract Classes Interfaces the Comparable Interface Interfaces vs Abstract Classes. Text IO Handled in Java
5.2 Abstract Classes Interfaces the Comparable Interface Interfaces vs Abstract Classes. Text IO Handled in Java
An abstract class is a class that cannot be instantiated and may contain abstract
methods (methods without a body). It serves as a base class for other classes.
// Concrete method
void sleep() {
System.out.println(name + " is sleeping.");
}
}
@Override
void makeSound() {
System.out.println(name + " barks!");
}
}
2. Interfaces in Java
An interface in Java defines a contract that a class must follow but does not contain any
concrete implementations.
Example of an Interface
interface Vehicle {
void start();
}
The Comparable interface is used for sorting objects in Java. It allows a class to define
a natural ordering by implementing the compareTo method.
Key Features
✅ Single-method interface: int compareTo(T obj).
✅ Used for sorting objects in collections (TreeSet, TreeMap, Arrays.sort(), etc.).
✅ Returns:
import java.util.*;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
✔ Use an abstract class when: You want to share code among related classes.
✔ Use an interface when: You want multiple classes to follow a common contract.
Java provides multiple ways to handle text input/output, including File Handling.
import java.io.*;
import java.io.*;