I tested as well after I thought I was going crazy.
Correct answer is DerivedA DerivedB
class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1 = new DerivedB();
Base b2 = new DerivedA();
Base b3 = new DerivedB();
Base b4 = b3;
b1 = (Base) b2;
b1.test();
b4.test();
}
}
Answer is "DerivedA DerivedB".
--------------------------------------------------
// Base.java
public class Base {
public void test() {
System.out.println("Base ");
}
}
-------------------------
// DerivedA.java
class DerivedA extends Base {
public void test() {
System.out.println("DerivedA ");
}
}
-------------------------
// DerivedB.java
class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1 = new DerivedB();
Base b2 = new DerivedA();
Base b3 = new DerivedB();
Base b4 = b3;
b1 = (Base) b2;
b1.test();
b4.test();
}
}
--------------------------------------------------
This question has no correct alternative as it prints "DerivedA DerivedB". What you have to pay in these questions is to which object the variable is pointing and we see this in the "new DerivedB", so we know that our B1 and B3 even being of the "Base" type they are "DerivedB" objects. the variable B4 is a reference of B3 which is a "DerivedB" object so we know that in the second position of the print it is a "DerivedB", even doing a cast of B2 -> Base the overload always takes the child's method then prints "DerivedA " getting "DerivedA DerivedB". To be honest, I don't know what to mark if this happens in the test, but I would mark the alternative that came closest to the truth, which is alternative B. The only one that came closest to the "b1.test()" method and hit the " b4.test()". If in doubt, follow the code:
class Base {
public void test() {
System.out.println("Base ");
}
}
class DerivedA extends Base {
public void test() {
System.out.println("DerivedA ");
}
}
public class DerivedB extends DerivedA {
public void test() {
System.out.println("DerivedB ");
}
public static void main(String[] args) {
Base b1 = new DerivedB();
Base b2 = new DerivedA();
Base b3 = new DerivedB();
Base b4 = b3;
b1 = (Base) b2;
b1.test();
b4.test();
}
}
upvoted 2 times
...
...
Log in to ExamTopics
Sign in:
Community vote distribution
A (35%)
C (25%)
B (20%)
Other
Most Voted
A voting comment increases the vote count for the chosen answer by one.
Upvoting a comment with a selected answer will also increase the vote count towards that answer by one.
So if you see a comment that you already agree with, you can upvote it instead of posting a new comment.
MPignaProTech
2 months, 2 weeks agoMPignaProTech
2 months, 3 weeks agoBelloMio
7 months, 1 week ago7df49fb
9 months, 3 weeks agoamit_lad88
1 year agopbbvr
1 year, 5 months agoEricausdresden
1 year, 5 months agocarloswork
2 years, 1 month agoiSnover
2 years, 3 months agoiSnover
2 years, 3 months ago