Professor Abdul-Quader
Project 1 Discussion / Intro to Classes
Questions?
Last time:
ArrayList is a class.
We can use the ArrayList class as the data type for our variables.
list and list2 are different objects of type ArrayListAnother way to define ArrayLists:
ArrayList<Integer> list = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
list.add(1);
System.out.println("List 1 size: " + list.size());
System.out.println("list 2 size: " + list2.size());What does this print out? Why?
list and list2 are different objects
size is an instance method.
object.method(parameters)How do we define our own data types?
public class MyClassSpecial methods that every class defines.
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
list1.add(10);
list2.add(10);
if (list1 == list2) {
System.out.println("The lists refer to the same object");
} else if (list1.equals(list2)) {
System.out.println("The two lists have the same contents:");
System.out.println(list1.toString());
// technically, we could just do:
// System.out.println(list1);
}Create a new file, call it “Time.java”. Create the class:
Inside the class, we can declare our instance variables, constructors, and instance methods. Declare three new variables:
These are instance variables. Each instance of the Time class will have their own variables (independent of all the other instances).
Now let’s give our class a constructor. We need an hour, minute, and whether it is AM or PM actually initialize our instance variables, so let’s pass them in as parameters.
In App.java:
public class App {
public static void main(String[] args) {
Time time = new Time(11, 2, "AM");
System.out.println(time); // this is not so great
}
}What happened?
println calls the toString method on the object.Implement the toString method. (Remember the issue if minute < 10?)
This method should return a String. It should not output anything!
public class MyClass in file MyClass.javaIllegalArgumentException!public Time(int currentHour, int currentMinute, String amOrPm) {
if (currentHour < 1 || currentHour > 12) {
throw new IllegalArgumentException("hour must be between 1 and 12");
} else {
hour = currentHour;
}
...
}Time’s problem.Clean up your constructor so that it checks if the hour, minute, and “AM” or “PM” variables are valid. Use constant class variables so that there are no “magic values”.
Variable declarations in Time class:
public Time(...).Java has several different visibility modifiers:
If the instance variables are public:
Time t = new Time(11, 59, Time.AM); // "11:59 AM"
t.hour = 53;
t.minute = -7;
t.amPm = "Hah! I tricked you!";
System.out.println(t);