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();
b1.test();
b2.test();
b3.test();
b1= (Base) b3;
b1.test();
Base b4 = (DerivedA) b3;
b4.test();
b1.test();
}
}
Casting doesn't change the object itself. In inheritance, we create new classes that inherit features of the superclass while polymorphism decides what form of method to execute.
Answer is C DerivedB DerivedB
Answer is C.
--------------------------------
//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();
b1 = (Base) b3;
Base b4 = (DerivedA) b3;
b1.test();
b4.test();
}
}
--------------------------------
class Base {
public void test() {
System.out.println("Base ");
}
}
public 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();
b1 = (Base)b3;
Base b4 = (DerivedA)b3;
b1.test();
b4.test();
}
}
Correct. There is no problem with the casting (implicit upcasting is actually optional).
upvoted 6 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.
v323rs
Highly Voted 4 years, 11 months agowalkietalkie
Highly Voted 4 years, 7 months agovic88
Most Recent 1 week, 5 days agoKolodets
1 year, 7 months agoVicky_65
1 year, 8 months agoodzio33
1 year, 11 months agoakbiyik
2 years agocarloswork
2 years agohhuo
2 years, 1 month agotapsshore
2 years, 4 months agojuipeng
2 years, 6 months agoMurad22
2 years, 7 months agohitdaroad
2 years, 7 months agohitdaroad
2 years, 7 months agoXalaGyan
2 years, 10 months agoCosminCof
3 years, 2 months agoletmein2
5 years, 6 months ago