Describe the output of the following program and explain why it is produced. pub
ID: 3559368 • Letter: D
Question
Describe the output of the following program and explain why it is produced.
public class Main {
public static void main (String[] args) {
Base b = new Derived ();
b.foo();
}
}
class Base {
public static void foo() { System.out.println("Base"); }
}
class Derived extends Base {
public void foo() { System.out.println("Derived"); }
}
Describe the output of the following program and explain why it is produced.
struct base {
virtual void foo(void) { cout << "base" << endl; }
}
struct derived : base {
void foo(void) { cout << "derived" << endl; }
}
int main(void) {
base *b = new derived;
b -> foo();
return 0;
}
Explanation / Answer
case 1
compilation error will occur because in base class foo is static and cannot be overidden in derived class
but if it is not static then output "Derived" will be produced because and object of base b will see than foo is overidden in the derived class and thus it will invoke the method of derived class
case 2
"derived" will be produced as output because and object of base struct b will see than foo is overidden in the derived struct and thus it will invoke the functor of derived class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.