Skip to content

Instantly share code, notes, and snippets.

@ericgroom
Last active September 28, 2017 18:05
Show Gist options
  • Save ericgroom/dde9c3d81b8617ca69cf7547eb14b655 to your computer and use it in GitHub Desktop.
Save ericgroom/dde9c3d81b8617ca69cf7547eb14b655 to your computer and use it in GitHub Desktop.
Correct and incorrect implementation of a subclass of bread. Note this isn't compilable due to having 3 public classes in the same file, if you separate them into separate files they should compile.
// base class
public class Bread {
private String name;
private int amount;
public Bread(String name, int amount) {
this.name = name;
this.amount = amount;
}
public int getAmount() {
return this.amount;
}
}
// incorrect
public class BrownBread extends Bread {
private String name;
private int amount;
protected static final double PRICE_PER_ITEM = 1.1;
public BrownBread(String name, int amount) {
// note that this.name and this.amount are never set by this constructor and thus have the values null and 0 respectively
super(name, amount);
}
public double calculateTypePrice() {
// this.amount will always be 0 since it is not set in the constructor
return this.amount * PRICE_PER_ITEM;
}
}
// correct
public class BrownBread extends Bread {
protected static final double PRICE_PER_ITEM = 1.1;
public BrownBread(String name, int amount) {
// this line is now correct because we will use the super class Bread's properties via getters and setters
super(name, amount);
}
public double calculateTypePrice() {
// super.getAmount() will call Bread's getAmount which is set in the constructor this time
// also note that this.getAmount() is equivalent to super.getAmount() since it is inhereted from Bread
// however in this case I like to use super because I find it more explicit where the method is originating from.
return super.getAmount() * PRICE_PER_ITEM;
}
}
// another possibility if you don't want to use getters/setters in a subclass
public class Bread {
// protected values are available in subclasses
protected String name;
protected int amount;
public Bread(String name, int amount) {
this.name = name;
this.amount = amount;
}
}
public class BrownBread extends Bread {
protected static final double PRICE_PER_ITEM = 1.1;
public BrownBread(String name, int amount) {
super(name, amount);
}
public double calculateTypePrice() {
return amount * PRICE_PER_ITEM;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment