This is a closed notes, closed book exam. All of the problems on this exam, refer to the additional classes that are displayed on the projection screen. You should assume that all of the classes are in a single directory. There are no syntax errors in the classes displayed on the screen.
Here is a description of the four problems, but the order has been changed. Part of the quiz is to determine which problem fits the description.
Here are the classes that were projected during the quiz.
class ClassOne{
public void print()
{
System.out.println( "inside ClassOne");
}
}
class ClassTwo extends ClassOne {
public void print()
{
System.out.println( "inside ClassTwo");
}
public void bar()
{
System.out.println("bar in ClassTwo called");
}
}
class ClassThree extends ClassOne {
public void foo()
{
System.out.println("In foo from ClassThree");
}
}
class Quiz3xProb1 {
public static void main(String[] args)
{
ClassThree three = new ClassThree();
three.print();
three.foo();
}
}
1
No errors. Output:
inside ClassOne In foo from ClassThree
class Quiz3xProb2 {
public static void main(String[] args)
{
ClassOne one = new ClassTwo();
ClassTwo two;
one.print();
// two = one; //need to cast superclass ref into subclass ref
two = (ClassTwo)one;
two.bar();
}
}
After adding the cast, this one works fine because one is actually referencing an object of type ClassTwo. Notice that the first call to print() actually calls the print() method in ClassTwo because that is what the object actualy is. This is an example of dynamic method dispatch. The output is:
inside ClassTwo bar in ClassTwo called
class Quiz3xProb3 {
public static void main(String[] args)
{
ClassOne one = new ClassOne();
ClassTwo two;
one.print();
// two = one;
two = (ClassTwo)one;
two.print();
two.bar();
}
}
As with the previous problem, we need to cast the ClassOne reference into the subclass, ClassTwo reference. This will fix the syntax error, however, in this case there will be a runtime class cast exception when the cast is attempted because one is not actually referring to a ClassTwo object.
class Quiz3xProb4 {
public static void main(String[] args)
{
ClassTwo two;
ClassThree three = new ClassThree();
two = three;
two.print();
}
}
There is no way to assign a ClassThree reference to a ClassTwo reference. This program cannot be repaired using casting.