Rohan G CollegeBoard Unit 5 Writing Classes
Week 9 Writing Classes
- Classes are a blueprint for instantiating objects. An object is an istance of a class, a class defines an abstract type, methods are the behaviors you get objects to perform. Constructors create the object, are a special method for object instantiation, default constructor has no arguements. Accessor methods are getters and setters, which allow you to get values of variables and return a copy, or edit a variable.
- Hack
Classes are a blueprint for instantiating objects. An object is an istance of a class, a class defines an abstract type, methods are the behaviors you get objects to perform. Constructors create the object, are a special method for object instantiation, default constructor has no arguements. Accessor methods are getters and setters, which allow you to get values of variables and return a copy, or edit a variable.
public class StepTracker {
// initialize variables
private int minActiveSteps;
private int totalSteps;
private int numTotalDays;
private int numActiveDays;
// set default construct
public StepTracker(int minActiveSteps) {
this.minActiveSteps = minActiveSteps;
this.totalSteps = 0;
this.numTotalDays = 0;
this.numActiveDays = 0;
}
// once per day, increment steps, days, and possibly active
public void addDailySteps(int numSteps) {
this.totalSteps += numSteps;
this.numTotalDays++;
if (numSteps >= this.minActiveSteps) {
this.numActiveDays++;
}
}
// getter
public int activeDays() {
return this.numActiveDays;
}
// calculate
public double averageSteps() {
if (numTotalDays == 0) {
return 0.0;
} else {
return (double) this.totalSteps/this.numTotalDays;
}
}
}
// FRQ #2
public class StepTracker {
private int totalSteps;
private int minimumSteps;
private int days;
private int activeDays;
public StepTracker(int min){
minimumSteps = min;
totalSteps = 0;
days = 0;
activeDays = 0;
}
public void addDailySteps(int steps){
totalSteps += steps;
days++;
if (steps >= minSteps){
activeDays++;
}
}
public double averageSteps(){
if (days == 0){
return 0.0;
}
else{
return (double) totalSteps / days;
}
}
public int getActiveDays(){
return days;
}
}
public class Cow {
public String type;
public String sound;
public int milk;
public Cow(String type, String sound, int milk) {
this.type = type;
this.sound = sound;
this.milk = milk;
}
public String getType() {
return this.type;
}
public String getSound() {
return this.sound;
}
public static void main(String[] args) {
Cow tommy = new Cow("white", "moo", 5);
Cow jacky = new Cow("black", "meow", 3);
System.out.println(tommy.getSound());
}
}
Cow.main(null);