Assignment 2: Delegation
Goals: Practice designing methods for interfaces, and employing delegation.
You should submit one .java file containing the solution to this problem.
Be sure to properly test your code and write purpose statements for your methods. A lack of tests and documentation will result in a lower grade! Remember that testing requires you to make some examples of data in an examples class.
If a method is declared in an interface and the implementing class’s method does not require extrapolation outside of the purpose statement in the interface, you do not need to provide a purpose statement for the method inside the class.
Remember to delegate to the class/interface that is primarily responsible for a given computation! Classes should talk to each other through methods, not through fields.
Problem 1
Here are some classes that represent pets and pet owners:
// a pet owner class Person { String name; IPet pet; int age; // in years Person(String name, IPet pet, int age) { this.name = name; this.pet = pet; this.age = age; } } // a pet interface IPet { } // a pet cat class Cat implements IPet { String name; int age; // in years Cat(String name, int age) { this.name = name; this.age = age; } } // a pet dog class Dog implements IPet { String name; int age; // in years Dog(String name, int age) { this.name = name; this.age = age; } } // no pet class NoPet implements IPet { }
Design a method older which ages a person and their pet (if there is one) by one year.
Design a method samePetName which determines if a person’s pet (if they have one) has the same name as a given String. To compare two strings in Java, use the boolean equals(String other) method on strings. Note: A NoPet does not have any name, including "" or, even worse, null. If you find that you have to program some notion of a NoPet having a name, you are not using proper delegation.
Design the interface and classes for a list of people, in accordance with the style seen in class.
Design a method which ages every person and their pet in the list by one year.
Design a method which computes the total age of all humans and pets in the list in human years. For the purposes of this problem, one year of a cat’s life is equal to six human years, and one year of a dog’s life is equal to seven human years.
Design a method anyNarcissists which determines if any pet owner in a list has named their pet after themselves. As a reminder, or is written with ||, which combines two boolean expressions, and is syntactically similar to &&. Note: Remember, classes talk to each other through methods, not fields. Delegate by writing new methods as needed, not accessing the fields of other classes!