0% found this document useful (0 votes)
12 views

5.2 Abstract Classes Interfaces the Comparable Interface Interfaces vs Abstract Classes. Text IO Handled in Java

The document explains abstract classes and interfaces in Java, highlighting their key features, differences, and usage scenarios. It covers the Comparable interface for sorting objects and provides examples of text input/output handling using BufferedReader and BufferedWriter. The comparison between abstract classes and interfaces clarifies when to use each in programming.

Uploaded by

Vedaang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

5.2 Abstract Classes Interfaces the Comparable Interface Interfaces vs Abstract Classes. Text IO Handled in Java

The document explains abstract classes and interfaces in Java, highlighting their key features, differences, and usage scenarios. It covers the Comparable interface for sorting objects and provides examples of text input/output handling using BufferedReader and BufferedWriter. The comparison between abstract classes and interfaces clarifies when to use each in programming.

Uploaded by

Vedaang Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

5.2 Abstract Classes, Interfaces, The Comparable Interface, Interfaces vs.

Abstract Classes. Text I/O Handled in Java

1. Abstract Classes 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.

Key Features of Abstract Classes

✅ Can have both abstract and concrete methods.


✅ Used for partial implementation of a class.
✅ Can have constructors, instance variables, and static methods.
✅ Uses the abstract keyword.

Example of an Abstract Class

abstract class Animal {


String name;

// Abstract method (no implementation)


abstract void makeSound();

// Concrete method
void sleep() {
System.out.println(name + " is sleeping.");
}
}

// Subclass providing implementation for the abstract method


class Dog extends Animal {
Dog(String name) {
this.name = name;
}

@Override
void makeSound() {
System.out.println(name + " barks!");
}
}

public class AbstractExample {


public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
myDog.makeSound(); // Output: Buddy barks!
myDog.sleep(); // Output: Buddy is sleeping.
}
}

2. Interfaces in Java

An interface in Java defines a contract that a class must follow but does not contain any
concrete implementations.

Key Features of Interfaces

✅ Contains only abstract methods (before Java 8).


✅ Uses the interface keyword.
✅ A class implements an interface using the implements keyword.
✅ Supports multiple inheritance (unlike abstract classes).
✅ From Java 8 onwards, interfaces can have default and static methods.

Example of an Interface

interface Vehicle {
void start();
}

// Implementing the interface


class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car engine starts...");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Vehicle myCar = new Car();
myCar.start(); // Output: Car engine starts...
}
}

3. The Comparable Interface

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:

 Negative value if this < obj


 Zero if this == obj
 Positive value if this > obj

Example of Comparable Interface

import java.util.*;

class Student implements Comparable<Student> {


String name;
int age;

Student(String name, int age) {


this.name = name;
this.age = age;
}

// Implement compareTo for sorting by age


@Override
public int compareTo(Student s) {
return Integer.compare(this.age, s.age);
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 20));
students.add(new Student("Charlie", 25));

// Sort list of students by age


Collections.sort(students);
System.out.println(students);
}
}

✅ Output: [Bob (20), Alice (22), Charlie (25)]


4. Interfaces vs. Abstract Classes

Feature Abstract Class Interface


Usage Partial implementation Fully abstract (before Java 8)
Methods Both abstract & concrete methods Only abstract methods (before Java 8)
Variables Can have instance variables Only public static final constants
Inheritance Supports single inheritance Supports multiple inheritance
Constructors Can have constructors Cannot have constructors

✔ 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.

5. Text I/O Handling in Java

Java provides multiple ways to handle text input/output, including File Handling.

Reading from a File (Using BufferedReader)

import java.io.*;

public class FileReadExample {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
}
}

Writing to a File (Using BufferedWriter)

import java.io.*;

public class FileWriteExample {


public static void main(String[] args) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
bw.write("Hello, Java File Handling!");
bw.newLine();
bw.write("This is a second line.");
} catch (IOException e) {
System.out.println("Error writing file: " + e.getMessage());
}
}
}

You might also like