Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose that we have classes A, B, C and D. Suppose that B is a subclass of A, t

ID: 3581443 • Letter: S

Question

Suppose that we have classes A, B, C and D. Suppose that B is a subclass of A, that C is a subclass of B, and D is a subclass of A. Suppose that we make the following declarations.

A a1 = new A();

A a2 = new C();

D d1 = new D();

For each part below, explain what, if any, errors would be caused by the statement in that part. Be sure to consider both compile time and run time errors.

(a) A a3 = new B();

(b) B b1 = new A();

(c) B b2 = (B) a1;

(d) B b3 = (B) a2;

(e) B b4 = (B) d1;

(f) B b5 = (C)(A)new D();

Explanation / Answer

Answer: In the above statements (a) , (b) , (c) , (d) , (e) & (f)

The statements (a) , (d) are successfully executed

The statements (c) & (f) are causes Run time Errors

for (c) Runtime Error: A cannot be cast to B

for (f) Runtime Error: D cannot be cast to C

The statements (b) & (e) are causes compile time Errors

(b) Error Incompatable types: A cannot be converted to B

(e) Error Incompatable types: D cannot be converted to B

Program:

import java.io.*;
class A
{
public int i;
public A()
{
System.out.println("Default constructor A() is called:");
i=10;
}
public void Adisplay()
{
System.out.println("In A class i="+i);
}
}
class B extends A
{
public int j;
public B()
{
System.out.println("Default constructor B() is called:");
j=20;
}
public void Bdisplay()
{
j=i+1;
System.out.println("In B class j="+j);
}
}
class C extends B
{
public int k;
public C()
{
System.out.println("Default constructor C() is called:");
k=30;
}
public void Cdisplay()
{
k=j+1;
System.out.println("In B class k="+k);
}
}
class D extends A
{
public int l;
public D()
{
System.out.println("Default constructor D() is called:");
l=40;
}
public void Ddisplay()
{
l=i+1;
System.out.println("In D class l="+l);
}
}
class MultiInheritance
{
public static void main(String args[])
{
System.out.println(" start of main()");
A a1 = new A();
A a2 = new C();
D d1 = new D();
//A a3 = new B(); //(a) successfully executed
//B b1 = new A(); //(b) Error Incompatable types: A cannot be converted to B
//B b2 = (B) a1; //(c) Runtime Error: A cannot be cast to B
//B b3 = (B) a2; //(d) successfully executed
//B b4 = (B) d1; //(e) Error Incompatable types: D cannot be converted to B
B b5 = (C)(A)new D(); //(f) Runtime Error: D cannot be cast to C

}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote