CS F213 Object Oriented Programming
Lab 5: Array List, Interface, Final Class and Inner
Class
Team OOP, Dept. of CSIS
Array List
Uses of Array List in Java are:
● An ArrayList is a resizable array, which is part of the java.util package.
● Unlike arrays in Java, which have a fixed size, an ArrayList can grow and
shrink dynamically as elements are added or removed.
● Key Characteristics of ArrayList:
1. Resizable: Automatically adjusts its size when elements are added or
removed.
2. Type-Safe: When using generics, you can specify the type of elements it
can contain, ensuring type safety at compile-time.
3. Indexed Access: Provides random access to elements using an index,
similar to arrays.
4. Null Elements: Allows null elements, just like any other Java collection.
StudentManager Class
Student Class import java.util.ArrayList;
public class StudentManager {
public static void main(String[] args) {
class Student { // Create an ArrayList to store Student objects
private String name; ArrayList<Student> students = new ArrayList<>();
private int age; // Add students to the ArrayList
students.add(new Student("Alice", 20));
public Student(String name, int age) {
students.add(new Student("Bob", 22));
this.name = name; students.add(new Student("Charlie", 19));
this.age = age; // Display information about all students
} for (Student student : students) {
public String getName() { student.displayInfo();
return name; }
students.remove(1); // Removes the student at index 1
} (Bob)
public int getAge() { System.out.println("\nAfter removal:");
return age; // Display information about the remaining students
} for (Student student : students) {
public void displayInfo() { student.displayInfo();
System.out.println("Name: " + name + ", Age: " }
// Check if a student named "Alice" exists in the list
+ age); boolean hasAlice = students.stream().anyMatch(s ->
} s.getName().equals("Alice"));
} System.out.println("\nContains Alice? " + hasAlice);
}}
Use previous
Student class
and main
class.
So how does Interface helps?
Uses of Interfaces in Java are:
● It is used to achieve total abstraction.
● Since java does not support multiple inheritances in the case of class,
by using an interface it can achieve multiple inheritances.
● Any class can extend only 1 class, but can any class implement an
infinite number of interfaces.
● It is also used to achieve loose coupling.
● Interfaces are used to implement abstraction.
Let us create two interfaces
was not there
before JDK 8
was not there
before JDK 8
Let us create a new class called FDCode
Let us create a new class called FDCode
varargs
Let us create a new class called FDCode
We need the extra utility function in global
Let us create a new class called FDCodeRobo
Now we run this main file
To get the following output
Final Class
In Java, the final keyword can be applied to a class, method, or variable, with
different meanings depending on the context. When applied to a class, it defines a
final class.
● A final class is a class that cannot be subclassed. In other words, no other
class can extend a final class.
● The primary purpose of making a class final is to prevent inheritance,
ensuring that the class’s implementation remains unchanged.
Final Class
// Final class
public final class FinalClass { Main Class
// Method in the final class
public class Main {
public void display() {
public static void main(String[] args) {
System.out.println("This is a // Create an instance of the final class
method in a final class."); FinalClass finalClassInstance = new
} FinalClass();
} finalClassInstance.display();
}
// Uncommenting the following code will }
cause a compilation error:
// class SubClass extends FinalClass {
// }
Final Method
● Prevents a method from being overridden in a subclass.
● The method can still be inherited, but it cannot be modified in the subclass
class SuperClass {
// Final method
public final void finalMethod() {
System.out.println("This is a final method.");
}
// Non-final method
public void nonFinalMethod() {
System.out.println("This is a non-final method.");
}}
Sub Class
class SubClass extends SuperClass {
// This will cause a compilation Main Class
error if uncommented:
// @Override
public class Main {
// public void finalMethod() {
// System.out.println("Cannot public static void main(String[] args) {
override a final method."); SubClass subclass = new SubClass();
// } subclass.finalMethod();
// Calls the final method from SuperClass
@Override subclass.nonFinalMethod();
public void nonFinalMethod() {
// Calls the overridden method from SubClass
System.out.println("Overridden
non-final method."); }
} }
}
Inner Class
An inner class in Java is a class that is defined within another class. It has access to all the members
(including private members) of the outer class. Inner classes are a powerful feature that allows you to
logically group classes that are only used in one place, increasing encapsulation and helping to maintain
cleaner, more readable code.
Types of Inner Classes:
● Member Inner Class: A non-static inner class defined at the member level of the outer class.
● Static Nested Class: A static inner class that behaves like a static member of the outer class.
● Local Inner Class: A class defined within a method or a block of code.
● Anonymous Inner Class: A class with no name, defined and instantiated in a single expression,
typically used for implementing interfaces or extending classes.
Inner Class
Advantages of Inner Classes
● Encapsulation: Inner classes allow you to logically group classes that belong together, improving
encapsulation.
● Readability: Code can be more readable and organized when related classes are grouped
together.
● Access to Outer Class Members: Inner classes can directly access the outer class's members,
simplifying the code.
When to Use Inner Classes
● When a class is useful only to one other class.
● When you want to hide a class from other classes in the same package.
● When you want to define helper classes that are used only by their enclosing classes.
Inner classes can make your code more modular and organized, especially when you have a complex
class structure with closely related functionalities.
Member Inner Class
● Defined inside a class but outside any method.
● It can access all members of the outer class, including private members.
class OuterClass { public class TestInnerClass {
private String outerField = "Outer"; public static void main(String[] args) {
OuterClass outer = new
class InnerClass { OuterClass();
void display() { OuterClass.InnerClass inner =
System.out.println("Outer field: " outer.new InnerClass();
+ outerField); inner.display(); // Accesses the
} outerField of OuterClass
} }
} }
Static Nested Class
● Defined as a static class inside another class.
● Unlike other inner classes, a static nested class does not have access to the instance
variables or methods of the outer class.
class OuterClass { public class TestStaticNestedClass {
private static String outerStaticField = public static void main(String[] args) {
"Outer Static"; OuterClass.StaticNestedClass
nested = new
static class StaticNestedClass { OuterClass.StaticNestedClass();
void display() { nested.display(); // Accesses the
System.out.println("Static outer static outer field of OuterClass
field: " + outerStaticField); }
} }
}}
Local Inner Class
● Defined within a method or a block of code.
● It can access the local variables of the method where it is defined, provided the
variables are final or effectively final.
class OuterClass {
void outerMethod() {
final String localVariable = "Local
Variable"; public class TestLocalInnerClass {
class LocalInnerClass { public static void main(String[] args) {
void display() { OuterClass outer = new
System.out.println("Local variable: " OuterClass();
+ localVariable); outer.outerMethod();
} } }
LocalInnerClass localInner = new }
LocalInnerClass();
localInner.display();
}}
Anonymous Inner Class
● A type of local inner class that is declared and instantiated in a single statement.
● Often used to provide a quick implementation of an interface or an abstract class.
public class TestAnonymousInnerClass {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
public void sayHello() {
interface Greeting {
System.out.println("Hello from
void sayHello();
an anonymous inner class!");
}
}
};
greeting.sayHello();
}
}
Your Tasks:
● Copy the code from Repo https://github.com/Aritra/OOPLabMaterials/ and
reuse code from Lab2 make this work.
● Add a printDetails() method to override [compile time polymorphism] to
FDCodeRobo class (just like it is done in FDCode, be creative!)
● Create another interface MusicClubMember and create a class
FDRoboMusic with obvious meaning. Be creative with the members and
functions.
● Create a similar HDCodeMusic class
Exercise
● Create a class Library with attributes: name (String) and location (String).
Inside the Library class, create a non-static inner class Book with attributes:
title (String) and author (String). The Book class should have a method
displayBookInfo() that prints the title, author, and the library name. The Library
class should have a method addBook() that creates a Book object and calls
displayBookInfo().
// Inner class
Solution: class Book {
private String title;
class Library { private String author;
private String name;
private String location; public Book(String title, String author) {
this.title = title;
this.author = author;
public Library(String name, String }
location) {
this.name = name; public void displayBookInfo() {
this.location = location; System.out.println("Library: " + name);
} System.out.println("Book Title: " + title);
System.out.println("Author: " + author);
}
public void addBook(String title, }
String author) { public static void main(String[] args) {
Book book = new Book(title, Library library = new Library("Central
Library", "Downtown");
author); library.addBook("The Great Gatsby", "F.
book.displayBookInfo(); Scott Fitzgerald");
} }
}
Take Home Questions…
Q1) Problem Statement:
Design a MobilePhone class that contains an inner class Battery and an interface Chargeable. The
Chargeable interface should have methods:
● void chargeBattery()
● int getBatteryLevel()
The Battery inner class should implement the Chargeable interface and maintain the battery percentage
(0-100%). The MobilePhone class should:
● Allow the battery to be charged incrementally.
● Track battery usage when calling, browsing, or listening to music, decreasing the battery level accordingly.
Also, maintain a history of charging events using an ArrayList. Each entry in the ArrayList should store the
time and percentage charged.
Q2) Problem Statement
You are tasked with designing a simple College Management System that tracks the academic progress and activities of a group of friends during their
college life. The system should use the following OOP concepts: ArrayList, Interface, Final Class, and Inner Class.
The system should consist of the following components:
I. Interface Person:
A. This interface should include the following methods:
1. String getName()
2. int getAge()
3. String getRole()
II. Class Friend (Implementing Person):
A. This class should represent a college student who is also a friend.
B. Attributes should include:
1. String name
2. int age
3. String department
4. double GPA (Grade Point Average)
C. Methods should allow:
1. Getting the friend's name, age, and role (student/friend).
2. Updating and retrieving the GPA.
3. Enrolling in and dropping courses.
D. Use an ArrayList to store a list of courses each friend is enrolled in.
I. Final Class Event:
A. This class represents a college event (such as a fest, seminar, or group study).
B. Attributes include:
1. String eventName
2. String eventDate
3. String eventType (either Academic, Cultural, or Sports)
C. Since events are the same for everyone, the class should be declared as final.
II. Class College:
A. This class manages the group of friends in the system. It should have:
1. An ArrayList of Friend objects representing all friends.
2. Methods to:
a) Add a new friend.
b) Display the details of all friends.
c) Organize an event.
d) Enroll friends in events based on their preferences (e.g., sports enthusiasts, academic-focused friends).
B. Use an Inner Class inside College to sort friends by their GPA and return the top 3 students.
III. Class Main:
A. This class should contain the main method to:
1. Add friends to the college.
2. Enroll friends in courses.
3. Organize events.
4. Display the top 3 students based on GPA.
5. Show details of all friends and their activities.