ProgrammingVery hardProduct-company placement · Java
What is printed?
What is printed?
// file a/P.java
package a;
public class P {
void f() { System.out.print("P"); } // package-private
public void call() { f(); }
}
// file b/C.java
package b;
public class C extends a.P {
void f() { System.out.print("C"); }
}
// in main:
new b.C().call();- A. C
- B. Compile-time error: f() in C cannot override f() in P
- C. PC
- D. P
Correct answer: D. P
A package-private method is not visible outside package a, so C.f does not override P.f; it is an unrelated new method. call() therefore invokes P's own f.
More OOP with C++ and Java questions
- What is printed? java String r = Stream.of(3, 1, 3, 2).distinct().sorted() .map(String::valueOf).collect(Collectors.joining("-"))…
- What is printed? java System.out.print(Optional.ofNullable(null).map(Object::toString).orElse("none") + " ")…
- What happens when this is compiled? java interface I { void a(); void b(); } abstract class P implements I { public void a() { } } class C…
- Which line fails to compile? cpp struct P { int x = 3; ostream& operator<<(ostream& os) { return os << x; } }; int main() { P p; cout <<…
- What is wrong with this program? cpp struct Buf { int p; Buf() : p(new int[4]) { } ~Buf() { delete[] p; } }; int main() { Buf a; Buf b =…
- What happens when this is compiled? cpp struct A { int v = 0; int& get() const { return v; } };