In: Computer Science
write exactly what the following code prints. Ensure that you write in the correct order. clearly distinguish scratch work from your final answer.
Public class Base{
public void m1(Base a){
System.out.println("Base m1");
a.m2();
}
public void m2(){
System.out.println("Base m2");
}
}
Public class Derived1 extends Base{
public void m1(Base b){
System.out.println("Derived1 m1");
}
public void m2(){
System.out.println("Derived1 m2");
}
}
Public class Derived2 extends Base{
public void m2(){
System.out.m2(){
System.out.println("Dertived2 m2");
}
}
public class UserBaseAndDerived1And2{
public static void main(String[] args){
Base b = new Base();
Derived1 d1 = new Derived1();
Derived2 d2 = new Derived2();
b.m1(b);
b.m1(d1);
b.m1(d2);
b =d1;
b.m1(d2);
b = d2;
b.m1(d1);
}
}
Output:
Base m1
Base m2
Base m1
Derived1 m2
Base m1
Dertived2 m2
Derived1 m1
Base m1
Derived1 m2
// here calling m1() with object type Base so it will execute
base class m1()
// from there we are calling m2
which executes in m2()
b.m1(b);
// here calling m1() with object
type Base so it will execute base class m1()
// passing d1 object if type
Dereived1 so m2() will called using d1 so it will execute m2() in
the Derived1 class
b.m1(d1);
// here calling m1() with object
type Base so it will execute base class m1()
// passing d2 object if type
Dereived2 so m2() will called using d1 so it will execute m2() in
the Derived2 class
b.m1(d2);
//now b is pointing to Derived1
class object
b = d1;
//calling m1() using b, now b is pointing Derived1 object so it
will execute m1() in Derived1
// calling m2() using d2 so it will call in Derived2 class
b.m1(d2);
// now b is pointing d2
b = d2;
// now m1() in Derived2 will be executed
// passing d1 so m2() will be executed in Derived1
b.m1(d1);