retagged by
5,424 views
2 votes
2 votes

Consider the following class definitions in a hypothetical Object Oriented language that supports inheritance and uses dynamic binding. The language should not be assumed to  be either Java or C++, though the syntax is similar.

Class P {
    Class Q subclass of P {
        void f(int i) {
            void f(int i) {
                print(i);
                print(2*i);
            }
        }
    }
}  

Now consider the following program fragment:

P x = new Q();

Q y = new Q();

P z = new Q();

x.f(1); ((P)y).f(1); z.f(1);

Here ((P)y) denotes a typecast of y to P. The output produced by executing the above program fragment will be

  1. 1 2 1
  2. 2 1 1
  3. 2 1 2
  4. 2 2 2
retagged by

2 Answers

3 votes
3 votes

Answer is D)

Inheritance will make sure every function in parent class P is also a part of Q. But since Q has overridden the function f, Q's definition of function f will be used whenever an object of type Q is used to call f.

Dynamic binding determines the type of the object at run-time and not compile time. Refer  http://www.javatpoint.com/static-binding-and-dynamic-binding

Looking at the pseudo code, in all the cases x.f(1), ((P) y), z.f(1), the objects are of type Q, hence function f from child class will be used. And since the definition of function f is present in parent class as well there wont be any exceptions.

Here's a small java example.

public class HelloWorld{
    public static void main(String []args){
        P x = new Q();
        Q y = new Q();
        P z = new Q();
        P w = new P();
        x.f(1);
        ((P) y).f(1);
        z.f(1);
    }  
}    
public class P {
    void f(int i) {
        System.out.println(i);
    }
}
public class Q extends P {
    void f(int i) {
        System.out.println(2*i);      
    }  
}
1 votes
1 votes
Answer-C)

this is polymorphism

Superclass object = new subclass(); <<-- object created for subclass referenced by a superclass

when anything invoked using this object (THIS IS IMPORTANT)

All the methods of superclass can be invoked which are not in subclass

AND when a method is invoked which is in both (overridden) the SUBCLASS Method will be called!!

Additional info-->

superclass to subclass requires EXPLICIT CASTING

subclass to superclass doesn't require explicit casting (although no problem if used)
Answer:

Related questions

5 votes
5 votes
0 answers
3
Kathleen asked Sep 17, 2014
3,746 views
Consider the following logic program P$\begin{align*} A(x) &\gets B(x,y), C(y) \\ &\gets B(x,x) \end{align*}$Which of the following first order sentences is equivalent to...