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

4. Subtyping, Interfaces, and Inheritance; Consider the following Java int defin

ID: 3781695 • Letter: 4

Question



4. Subtyping, Interfaces, and Inheritance; Consider the following Java int definitions: [10 points] public interface X int getX public interface Y int get Y class c mplements x public int getX return class D extends c implements Y public int getX return 2; public int get return getx getX class E extends C public int get YO return 3; For each code snippet below write the integer value that will be printed out, or wr the compiler would generate an error. a) x System. new co b) x out println (x1.getx0); System. new out.println (x2 get c) Y new cry System. out println (yl get Y d) c system out println cl. get new Drs D System. new D out print in (dl get Y i

Explanation / Answer

Q4

A- X x1=new C();
System.out.print(x1.getX());

output - 1

B-

X x2=new D();
System.out.print(x2.getY());

output- Error because interface X cannot call getY as it is defined in interface Y.

C-

Y y1=new C();
System.out.print(y1.getX())

output - Error because not interfaceY is calling a method which is defined in method X so it will not compile .

D-

C c1=new D();
System.out.print(c1.getX());

output - 2 because super calling a sub class object so it can be done .

E-

D d1=new D();
System.out.print(d1.getY());

output - 4.

Q5-

output -

2

4

6

8

Stack<Integer> s = new Stack<Integer>(); \ creates a stack of integer type

s.push(1); \ Pushes 1 on the top of stack
for(int i=2;i<=5;i++){ \ loop from i=2 to 5
int val=s.peek(); \ value at the top is stored in variable val
s.push(i); \ now i = 2 is pushed at the top of the stack
s.push(val*2); now val=1 is multiplied with 2 now the top of stack is 2 and the first value is also 2
System.out.print(s.pop() + " "); value at the top is popped out .
System.out.println();

Q6-

class E
{
void mystery(int x, int y)
{
if(x>y){
System.out.print("*");
}
else if(x==y){
System.out.print("="+ y + "=");
}
else
{
System.out.print(y + " ");
mystery(x+1,y-1);
System.out.print(" " + x);
}}}
class F
{
public static void main(String args[])
{
E e=new E();
e.mystery(3,7);
}}

output will be - 7 6 =5= 4 3

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