- Suppose you have an interface called ShakesHands with the following
method listed in that interface:
public void shakeHands(ShakesHands other);
and three classes (Student, Teacher, Parent) all of which implement the
ShakesHands interface,
determine which of the following code fragments would compile:
ShakesHands x = new ShakesHands();
ShakesHands x = new Student();
Student x = new ShakesHands();
Student x = new Teacher();
ShakesHands x;
x = new Student();
x = new Teacher();
x = new Parent();
Teacher x = new Teacher();
Teacher y = new Teacher();
x.shakeHands(y);
Student x = new Student();
Teacher y = new Teacher();
x.shakeHands(y);
Parent x = new Parent();
String y = new String("Parent");
x.shakeHands(y);
ShakesHands x = new Student();
x.shakeHands(x);
- Assuming you have a class named Rational where each object
contains two ints representing the numerator and the denominator, write
the class definition line if you wanted to indicate that it would
implement the generic interface Comparable<Rational> and
write the body of the required method with the signature:
public int compareTo(Object other);
so that it will only return -1 or 0 or +1 based on the relative order
of the two objects based on the numerators and denominators.
- Assuming a variable theList refers to an
ArrayList<String>, which of the following lines of code
would compile?
theList.add("Hello");
theList.add(new String("Hello"));
theList.add(new StringBuffer("Hello"));
theList.add(100);
- What would be the output from the following code segment?
ArrayList listOne = new ArrayList();
listOne.add(new StringBuffer("One");
listOne.add(new StringBuffer("Two");
listOne.add(new StringBuffer("Three");
ArrayList listTwo = new ArrayList(listOne);
listOne.add(new StringBuffer("Four");
for (StringBuffer str : listTwo) {
str.append("2");
}
System.out.println("List One: " + listOne);
System.out.println("List Two: " + listTwo);
- Imagine an interface called Animal as follows:
public interface Animal {
public String getName();
public void setName(String s);
public String makeSound();
public String toString();
}
Write a class named Cat that implements this interface,
has an instance field to store the name, has a constructor
and copy constructor.
The class should also have an instance field for keeping
track of the number of mice the cat has caught, and
public methods caughtAnother() and int getMouseCount()
to allow other code to interact with that count.