☰ Contents Abstract Classes and Mutation

Abstract Classes and Mutation in Summary

With the posts from the first step, where Message is an abstract class, which line does not compile?
  1. Post m = new Message("ben", "My cat learns Java", 7);
    Message is abstract, so new Message(...) is a compile error. Its constructor only runs through super(...) in a subclass.
  2. Post v = new VideoPost("ben", "My cat learns Java", 7, 42);
    VideoPost is not abstract and gives its own preview, so it can be constructed.
  3. Message t = new TextPost("cse11", "Exam moved to Friday", 12, true);
    A variable can have an abstract class as its type. The object in it is a TextPost.
Still with the posts from the first step, and Post v = new VideoPost("ben", "My cat learns Java", 7, 42);:
v.snippet() runs the one in
v.preview() runs the one in
v.snippet() returns

What happens with this class?

class Post {
  final int likes;
  Post(int likes) { this.likes = likes; }
  void like() { this.likes = likes + 1; }
}
  1. It does not compile, because of the line in like
    A final field can only be assigned in the constructor. Java reports cannot assign a value to final variable
    likes
    .
  2. It does not compile, because of the line in the constructor
    Assigning a final field inside the constructor is exactly what’s allowed; that’s how it gets its value.
  3. It compiles, and like leaves likes the same
    Java checks final when it compiles, so the program never gets to run.

With the Post, RepostCopy, and RepostRef classes from the sharing step:

Post p = new Post("joe", "CSE-PACE next Tuesday!", 22);
p.like();
RepostCopy copy = p.repostCopy("ana");
RepostRef ref = p.repostRef("ben");
p.like();
p.like();
copy.likes is
ref.original.likes is