Quiz J2-1
Submit your answers via this Google Form
Question 1
What is the output of the below program?
class A {
public String toString(){
return "A";
}
}
class B extends A{
public String toString() {
return "B";
}
}
class C extends A {
public String toString() {
return super.toString();
}
}
class D extends C {
public String toString() {
return super.toString();
}
}
public class tmp{
public static void main(final String args[]) {
D d = new D();
System.out.println(d.toString());
}
}
Question 2
Consider the below program. What is the output?
class A {
public String toString(){
return "A";
}
public String fancyToString() {
return "~~A~~";
}
}
class B extends A{
public String toString() {
A letterA = this;
return letterA.fancyToString();
}
public String fancyToString(){
return "~~B~~";
}
}
public class LetterPrinter{
public static void main(final String args[]) {
B letterB = new B();
System.out.print(letterB.toString()+ " ");
A letterA = letterB;
System.out.println(letterA.toString());
}
}
Question 3
What if class B
’ did not implement a toString
method, like in below?
class B extends A{
public String fancyToString(){
return "~~B~~";
}
}
Question 4
What is the output of the program below?
class A{
public String toString(){
return "A";
}
}
class B extends A{
public String toString(){
return "B";
}
}
public class PolymorphicOverload{
public void foo(B letterB1, B letterB2) {
// 2
System.out.println("foo2: " + letterB1 + " " + letterB2);
}
public void foo(A letterA1, A letterA2){
//1
System.out.println("foo1: " + letterA1 + " " + letterA2);
}
public static void main(String args[]){
PolymorphicOverload f = new PolymorphicOverload();
B letterB = new B();
A letterA = (A) new B();
f.foo(letterB, letterA);
}
}