Writing Classes Lessons
Learnings and application to FRQ
- 5.1 Anatomy of a Class
- 5.2 Constructors
- 5.3 Comments
- 5.4 Accessor Method
- 5.5 Mutator Method
- 2019 FRQ Question 2
5.1 Anatomy of a Class
- Class: blueprint used to create objects
- Instances, attributes, constructors, methods
- Objects: instances of a class
- public: no restricted access -- classes and constructors
- private: restrict access -- instance variables
5.2 Constructors
- initializes instance variables when an object is created
- Each object has attributes which are the instance of a class
- Constructors set the initial state of an object by assigning initial values to instance variables
5.3 Comments
- ignored by compiler
- make code more readable
- not required for the AP exam
5.4 Accessor Method
- Allows objects outside of the class to obtain values
- non void returns a single value
- toString() Method
5.5 Mutator Method
- Don't return values
- Must be used when different classes need to modify instance variables
public class cow {
}
Cow myCow = new Cow();
public class Snack{
private String name; // instance variable 1
private int calories; // instance variable 2
public Snack(){ // constructor with no argument
name = null;
calories = 0;
}
public Snack (String n, int c){
name = n;
calories = x;
}
public String getName(){ // calling a method and accessor
return name;
}
public int getCalories(){
return calories;
}
public void setName(String n){
name = n;
}
public static void main(String[] args){
Snack one = new Snack("Chips", 100);
System.out.println(one.getName());
}
}
Snack.main(null);
public class StepTracker
{
private int minSteps;
private int totalSteps;
private int numDays;
private int numActiveDays;
public StepTracker(int threshold)
{
minSteps = threshold;
totalSteps = 0;
numDays = 0;
numActiveDays = 0;
}
public void addDailySteps(int steps)
{
totalSteps += steps;
numDays++;
if (steps >= minSteps)
{
numActiveDays++;
}
}
public int activeDays()
{
return numActiveDays;
}
public double averageSteps()
{
if (numDays == 0)
{
return 0.0;
}
else
{
return (double) totalSteps / numDays;
}
}
}