0/30 Days Completed 0 Learning Days
Day 27 of 30 · Week 4 — OOPs Through Java
Packages
1 Learn
A package is a folder-like group of related classes, e.g. college.library. It avoids name clashes and keeps projects tidy.
The package statement is the first line of a file. Use import to use a class from another package. java.lang (String, System) is imported automatically.
2 See the Code
Java
// File: college/library/Book.java
package college.library;
public class Book {
public String title;
public Book(String title) { this.title = title; }
}
// File: college/App.java
package college;
import college.library.Book;
import java.util.ArrayList;
public class App {
public static void main(String[] args) {
ArrayList<Book> list = new ArrayList<>();
list.add(new Book("Code Garden"));
System.out.println(list.get(0).title);
}
}- Book lives in package college.library.
- import college.library.Book lets App use Book by its short name.
- ArrayList comes from the built-in package java.util.
Output
Code Garden
3 Practice
- Plan a package structure for a college app: which packages would you create for students, fees and exams?
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. Where does the package statement go?
2. Which package is imported automatically?
Step 5
Answer and check the Quick Check above to unlock this.