Social media
unknown
java
a month ago
3.5 kB
1
Indexable
Never
Interfaces java Copy code // User Interface public interface IUser { String getUsername(); void setUsername(String username); void postMessage(String message); void follow(IUser user); void unfollow(IUser user); } // Post Interface public interface IPost { String getContent(); void setContent(String content); IUser getAuthor(); void addComment(IComment comment); List<IComment> getComments(); } // Comment Interface public interface IComment { String getContent(); void setContent(String content); IUser getAuthor(); } Implementations java Copy code import java.util.ArrayList; import java.util.List; // User Implementation public class User implements IUser { private String username; private List<IUser> following; private List<IPost> posts; public User(String username) { this.username = username; this.following = new ArrayList<>(); this.posts = new ArrayList<>(); } @Override public String getUsername() { return username; } @Override public void setUsername(String username) { this.username = username; } @Override public void postMessage(String message) { IPost post = new Post(message, this); posts.add(post); } @Override public void follow(IUser user) { if (!following.contains(user)) { following.add(user); } } @Override public void unfollow(IUser user) { following.remove(user); } } // Post Implementation public class Post implements IPost { private String content; private IUser author; private List<IComment> comments; public Post(String content, IUser author) { this.content = content; this.author = author; this.comments = new ArrayList<>(); } @Override public String getContent() { return content; } @Override public void setContent(String content) { this.content = content; } @Override public IUser getAuthor() { return author; } @Override public void addComment(IComment comment) { comments.add(comment); } @Override public List<IComment> getComments() { return comments; } } // Comment Implementation public class Comment implements IComment { private String content; private IUser author; public Comment(String content, IUser author) { this.content = content; this.author = author; } @Override public String getContent() { return content; } @Override public void setContent(String content) { this.content = content; } @Override public IUser getAuthor() { return author; } } Main Class java Copy code public class Main { public static void main(String[] args) { IUser alice = new User("Alice"); IUser bob = new User("Bob"); alice.follow(bob); alice.postMessage("Hello, world!"); IPost alicePost = ((User)alice).getPosts().get(0); IComment comment = new Comment("Nice post!", bob); alicePost.addComment(comment); System.out.println(alicePost.getContent() + " by " + alicePost.getAuthor().getUsername()); for (IComment c : alicePost.getComments()) { System.out.println("Comment: " + c.getContent() + " by " + c.getAuthor().getUsername()); } } }
Leave a Comment