Unit 5 - Writing Classes
public class StepTracker {
private int days;
private int activeDays;
private int totalSteps;
private int minActive;
public StepTracker(int m) {
minActive = m;
days = 0;
activeDays = 0;
totalSteps = 0;
}
public int activeDays() {
return activeDays;
}
public double averageSteps() {
if (days == 0) {
return 0.0;
}
return double totalSteps / days;
}
public void addDailySteps(int steps) {
days++;
totalSteps += steps;
if (steps >= minActive) {
activeDays++;
}
}
}
public class Cow {
// instance variables
private String cowType;
private String sound;
private int numMilkings;
// constructor
public Cow (String cowType, String sound){
this.numMilkings = 0;
this.cowType = cowType;
this.sound = sound;
}
}
public class Cow {
// instance variables
private String cowType;
private String sound;
private int numMilkings;
// default constructor
public Cow(){
this.numMilkings = 0;
this.cowType = null;
this.sound = null;
}
// all-args constructor
public Cow(String cowType, String sound, int numMilkings){
this.numMilkings = numMilkings;
this.cowType = cowType;
this.sound = sound;
}
public Cow (String cowType, String sound){
this.numMilkings = 0;
this.cowType = cowType;
this.sound = sound;
}
public static void main(String[] args) {
Cow firstCow = new Cow("holstein", "moo");
Cow secondCow = new Cow();
Cow thirdCow = new Cow("holstein", "moo", 100);
}
}
Cow.main(null);
Constructors -
- Default Constructor: no parameters
- Sets instance variables equal to default values
- String: null
- Int/Double: 0
- Java provides a no-argument default constructor if there are no constructors inside the class
- Instance variables set to default values
- Sets instance variables equal to default values
Procedural Abstraction Tip -
- When you see repeated code, that is a signal for you to make a new method!
- Benefits -
- organize our code by function
- reduce complexity
- reduce the repetition of code
- reuse code by putting it in a method and calling it whenever needed
- help with debugging and maintenance
- changes to that block of code only need to happen in one place
// Step 1
Classname objectName = new Classname();
// Step 2
objectName();
//Step 3
// method header
public void methodName() {
// method body for the code
}
public class Cow {
// instance variables
private String cowType;
private String sound;
private int numMilkings;
public Cow (String cowType, String sound){
this.numMilkings = 0;
this.cowType = cowType;
this.sound = sound;
}
public int getNumMilkings(){
return numMilkings;
}
public void setSound(String sound){
this.sound = sound;
}
public String toString(){
return "Type of Cow: " + cowType + "; " + "Sound: " + sound + "; " + "Number of Milkings: " + numMilkings;
}
public static void main(String[] args) {
Cow firstCow = new Cow("holstein", "moo");
System.out.println(firstCow);
System.out.println("Number of Milkings: " + firstCow.getNumMilkings());
firstCow.setSound("oink!");
System.out.println("Mutated Cow:" + firstCow);
}
}
Cow.main(null);