Java
Adding comments
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.
Exercise 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());.
Show example 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());
}
}
Test yourself
-
What kind of relation is the Post-Comment link?
- Composition
- Inheritance
- Dependency
- Abstraction
Show answer
Composition — A Post is made of Comments; this is composition.
-
Match the Post-Comment relation
- composition
- Post contains its Comments
- List<Comment>
- Comment collection type
- addComment
- Adds a comment
- comments.size()
- Number of comments
-
Complete the add-comment call
p.add____(new Comment("Mehmet", "Nice"));
Show answer
p.addComment(new Comment("Mehmet", "Nice"));
Next lesson: Search and filter