Adding comments
- Java course
- Intermediate
- Lesson 67/116
- 6 min
Write the comment flow with addComment.
Linking comments to a post
To add comments to a blog post, we extend the Post class with a List<Comment> comments field. Each post then carries its own comments. The addComment(Comment c) method appends a new comment to the list.
This design creates a composition between Post and Comment: a Post is made of Comments. Comment stays an independent class; one Comment can be reused on several posts.
The addComment method
The addComment method works like addPost: it appends the comment with comments.add(c);. You call it with post.addComment(new Comment(...)).
Since each Post keeps its own comment list, comments added to different posts do not mix. Use post.comments.size() to learn how many comments a post has.
Practice Add a comments field and addComment to Post
Add a List<Comment> comments = new ArrayList<>(); field to the Post class and a void addComment(Comment c) method that calls comments.add(c);. In main, create a Post p = new Post("First", "Ayşe");, add a comment with p.addComment(new Comment("Mehmet", "Nice"));, and print the comment count with System.out.println(p.comments.size());.
Starter code
import java.util.List;
import java.util.ArrayList;
class Post {
String title;
String author;
Post(String title, String author) {
this.title = title;
this.author = author;
}
}
class Comment {
String author;
String text;
Comment(String author, String text) {
this.author = author;
this.text = text;
}
}
// Add comments field and addComment method to Post
// main: create a Post, add a comment and print the countSample solution
class Post {
String title;
String author;
List<Comment> comments = new ArrayList<>();
Post(String title, String author) {
this.title = title;
this.author = author;
}
void addComment(Comment c) { comments.add(c); }
}
class Comment {
String author;
String text;
Comment(String author, String text) {
this.author = author;
this.text = text;
}
}
public class Main {
public static void main(String[] args) {
Post p = new Post("First", "Ayşe");
p.addComment(new Comment("Mehmet", "Nice"));
System.out.println(p.comments.size());
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of relation is the Post-Comment link?
- Composition Correct answer
- Inheritance
- Dependency
- Abstraction
Explanation: A Post is made of Comments; this is composition.
2 Match the Post-Comment relation
| Term | Meaning |
|---|---|
composition |
Post contains its Comments |
List<Comment> |
Comment collection type |
addComment |
Adds a comment |
comments.size() |
Number of comments |
3 Complete the add-comment call
p.add____(new Comment("Mehmet", "Nice"));
p.addComment(new Comment("Mehmet", "Nice"));
Explanation: The addComment method appends a new comment to the list.