Question

In: Computer Science

Given the following Java code: class C { public int foo(C p) { return 1; }...

Given the following Java code:

class C {
    public int foo(C p) { return 1; }
}

class D extends C {
    public int foo(C p) { return 2; }
    public int foo(D p) { return 3; }
}

C p = new C();
C q = new D();
D r = new D();

int i = p.foo(r);
int j = q.foo(q);
int k = q.foo(r);

(Remember that in Java every object is accessed through a pointer and that methods are virtual by default.)

Which methods get called in the three calls, i.e., what are the values of i, j, and k? Explain how the method selection works to result in these values.

Solutions

Expert Solution

For this statement, C p = new C(); , p object is created for class C as we have directly declared it.

Now for the second statement i.e., C q = new D(); ,since D is extending properties of C using inheritance, the object is created for class D i.e., q points to class D but of type class C.

Now in the similar way, the third statement i.e., D r = new D(); , here also the object is directly created to class D itself.

Now to compute i value in statement int i = p.foo(r); => p is object of class C and hence foo() in class C i.e.,

public int foo(C p) { return 1;  } gets invoked and value of 1 is returned.

Now to compute j value in statement int j=q.foo(q); => q is object of class D but type of class C and hence foo() in class D i.e.,

public int foo(C p) { return 2;  } gets invoked and value of 2 is returned.

Now to compute k value in statement int k=q.foo(r); => q is object of class D but type of class C and r is object of class D and hence foo() in class D i.e.,

public int foo(C p) { return 2;  } gets invoked and value of 2 is returned.

This is happening because of method overriding.

So the output will be

i=1

j=2

k=2


Related Solutions

1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int...
1. Convert the following code shown below to C++ code: public class HighwayBillboard { public int maxRevenue(int[] billboard, int[] revenue, int distance, int milesRes) { int[] MR = new int[distance + 1]; //Next billboard which can be used will start from index 0 in billboard[] int nextBillBoard = 0; //example if milesRes = 5 miles then any 2 bill boards has to be more than //5 miles away so actually we can put at 6th mile so we can add...
1. Consider the following code: public class Widget implements Serializable { private int x; public void...
1. Consider the following code: public class Widget implements Serializable { private int x; public void setX( int d ) { x = d; } public int getX() { return x; } writeObject( Object o ) { o.writeInt(x); } } Which of the following statements is true? I. The Widget class is not serializable because no constructor is defined. II. The Widget class is not serializable because the implementation of writeObject() is not needed. III. The code will not compile...
GIVEN THE CODE BELOW Given the following class: /** * Document class. */ public class Document...
GIVEN THE CODE BELOW Given the following class: /** * Document class. */ public class Document { private int words; /** * constructor * pre: none * post: A Document object created. Words initialized to 0. */ public Document() { words = 0; //default words } /** * Changes the number of document words. * pre: none * post: Words has been changed. */ public void setWords(int numWords) { words = numWords; } /** * Calculates the number of pages....
I needv pseudocode and a flowchart for the following java code public class AcmePay { public...
I needv pseudocode and a flowchart for the following java code public class AcmePay { public static void main(String[] args) throws Exception { Scanner scanner = new Scanner(System.in); int hours, shift, retirement = 0; do { System.out.print("Enter the number of hours worked (>0): "); hours = scanner.nextInt(); } while (hours <= 0); do { System.out.print("Enter shift [1 2 or 3]: "); shift = scanner.nextInt(); } while (shift < 1 || shift > 3); if (shift == 2 || shift ==...
class Arrays1{ public int getSumOfValues(int[] arr){ // return the sum of values of array elements int...
class Arrays1{ public int getSumOfValues(int[] arr){ // return the sum of values of array elements int sum = 0; int i; for(i = 0; i < arr.length; i++){ sum += arr[1]; } return sum; } public int getAverageValueInArray(int[] arr){ // return the average value of array elements int value = 0; for(int i = 0; i < arr.length; i++){ double average = value/ arr.length; } return value; } public int getNumberOfEvens(int[] arr){ //return the number of even values found in...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class...
Can someone please convert this java code to C code? import java.util.LinkedList; import java.util.List; public class Phase1 { /* Translates the MAL instruction to 1-3 TAL instructions * and returns the TAL instructions in a list * * mals: input program as a list of Instruction objects * * returns a list of TAL instructions (should be same size or longer than input list) */ public static List<Instruction> temp = new LinkedList<>(); public static List<Instruction> mal_to_tal(List<Instruction> mals) { for (int...
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
Stack2540Array   import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY...
Stack2540Array   import java .io .*; import java . util .*; public class Stack2540Array { int CAPACITY = 128; int top ; String [] stack ; public Stack2540Array () { stack = new String [ CAPACITY ]; top = -1; } 1 public int size () { return top + 1; } public boolean isEmpty () { return (top == -1); } public String top () { if ( top == -1) return null ; return stack [ top ]; }...
The following code is included for the java programming problem: public class Bunny {        private...
The following code is included for the java programming problem: public class Bunny {        private int bunnyNum;        public Bunny(int i) {               bunnyNum = i;        }        public void hop() {               System.out.println("Bunny " + bunnyNum + " hops");        } } Create an ArrayList <????> with Bunny as the generic type. Use an index for-loop to build (use .add(….) ) the Bunny ArrayList. From the output below, you need to have 5. Use an index for-loop...
In Java, please write a tester code. Here's my code: public class Bicycle {     public...
In Java, please write a tester code. Here's my code: public class Bicycle {     public int cadence; public int gear;   public int speed;     public Bicycle(int startCadence, int startSpeed, int startGear) {         gear = startGear;   cadence = startCadence; speed = startSpeed;     }     public void setCadence(int newValue) {         cadence = newValue;     }     public void setGear(int newValue) {         gear = newValue;     }     public void applyBrake(int decrement) {         speed -= decrement;    ...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT