Objects Examples Class #1 On the back of this sheet are two Java classes, Date and Dog.
public class DateTest {
public static void main(String[] args) {
Date today = new Date(7,10,2019); // Line A
Copyright By PowCoder代写 加微信 powcoder
System.out.println(today.formatDate()); // Line B
today.incrementDay(); // Line C
System.out.println(today.formatDate()); // Line D
today = new Date(7,10,2019);// Line E
Date nye = new Date(31,12,2018);
Date nye2 = nye; // Line F
System.out.println(nye.formatDate()); // Line G
nye.incrementDay();
System.out.println(nye2.formatDate()); // Line H
Dog dog = new Dog(new Date(14,10,2014),”Poodle”,”Min”); // Line I
System.out.println(dog.sayHello());
System.out.println(dog.getName() + ” is ” + dog.ageInYears(today) +
” years old”); // Line J
1. On the code, label the: Constructor, getters, and class attributes.
2. Why do we have ¡°this¡±? And why do we need getters?
3. What is created on line A?
4. What is the *exact* output of line B.
5. Trace through the program what happens on line C.
6. What is the *exact* output of line D?
7. What happens at Line E?
8. What happens at Line F?
9. What¡¯s the output at line H, and why?
10. What happens when we make an object within a call to a method as on Line I?
11. Work out what happens when dog.ageInYears() is called by sketching out the various
public class Date {
private int day,month,year;
public Date(int day, int month, int year) {
this.day = day;this.month = month;this.year = year;
public String formatDate() {
return String.format(“%02d/%02d/%4d”,day,month,year);
public int getYear() { return year;}
public int getMonth() { return month;}
public int getDay() { return day;}
public void incrementDay() {
this.day += 1;
if(day > 30 && (month == 4 || month == 6 || month == 9 || month ==
month += 1;day = 1;}
else if(day > 28 && month == 2) {month += 1;day = 1;}
else if(day > 31) { month += 1;day = 1;}
if(month == 13) {year += 1;month = 1;}
public int yearsDiff(Date other) {
int yearsDiff = (year – other.getYear()) – 1;
if(month > other.getMonth()) { yearsDiff += 1;}
else if(this.month == other.getMonth()) {
if(this.day >= other.getDay()) {yearsDiff += 1;}
return yearsDiff;
public class Dog {
private Date dob;
private String breed;
private String name;
public Dog(Date dob,String breed,String name) {
this.dob = dob;this.breed = breed;this.name = name;
public String sayHello() {
String output = “Hello, I’m a ” + breed + ” called ” + name;
output += ” and my dob is ” + dob.formatDate();
return output;
public String getName() { return name;}
public int ageInYears(Date today) {
return today.yearsDiff(dob);
This figure shows objects and scopes for part 11….
Note that I have not listed all variables / attributes that exist in each scope, just the relevant ones for this example….
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com