☰ Contents Extending Classes

Extending Classes in Summary

Using the feed classes, whose method body runs for each call on Repost r = new Repost("Free pizza in the CSE lobby", "tritons");?
Object
toString()
equals(Object o)
Message
String message
preview()
mentions(String word)
Repost
String from
↑ preview()
VideoPost
int seconds
↑ preview()
interface
Post
preview()
mentions(String word)
r.preview() runs the one in
r.mentions("pizza") runs the one in
r.toString() runs the one in
With Post p = new VideoPost("My cat learns Java", 42);, which of these are true? Select all that are.
  1. p instanceof VideoPost
    The object’s own class is VideoPost.
  2. p instanceof Message
    VideoPost extends Message, one step up the diagram.
  3. p instanceof Post
    Message implements Post, so the search finds it going up.
  4. p instanceof Object
    Every class ends up at Object, at the top of the diagram.
  5. p instanceof Repost
    Repost is a sibling of VideoPost, not above it, so the search going up never reaches it.

This BusStop leaves out super(lat, lng). What happens?

class Location {
  double lat;
  double lng;
  Location(double lat, double lng) {
    this.lat = lat;
    this.lng = lng;
  }
}
class BusStop extends Location {
  int route;
  BusStop(int route, double lat, double lng) {
    this.route = route;
  }
}
  1. It doesn’t compile
    A subclass constructor has to run a Location constructor first. Without a super(...), Java tries Location() with no arguments, and there isn’t one.
  2. It compiles, and lat and lng start at 0.0
    Java never leaves inherited fields unset because a constructor skipped them. It requires a Location constructor to run, and this one has no super(...).
  3. It compiles, and Java passes lat and lng to Location by itself
    Java doesn’t pass arguments along on its own. Every subclass constructor in this chapter wrote super(...) for that reason.
Finish Location’s equals: two Locations are equal when their lat and lng match, and nothing else equals a Location.
class Location {
double lat;
double lng;
Location(double lat, double lng) {
this.lat = lat;
this.lng = lng;
}
@Override
public boolean equals(Object other) {
if (this == other) { return true; }
if () { return false; }
Location l = ;
return lat == l.lat && lng == l.lng;
}
}
Location geisel = new Location(32.8811, -117.2376);
boolean same = geisel.equals(new Location(32.8811, -117.2376));
boolean notString = geisel.equals("Geisel Library");
boolean different = geisel.equals(new Location(32.7341, -117.1446));