c. Suppose a program contains the following lines of code: … Bar b = new Bar(\"T
ID: 3805094 • Letter: C
Question
c. Suppose a program contains the following lines of code:
…
Bar b = new Bar("This is a","test");
Foo f = (Foo) b;
FooUtils.fooCheck(b);
FooUtils.fooCheck(f);
The calls FooUtils.fooCheck(b); and FooUtils.barCheck(f) use static dispatch as discussed in class. Explain in 2-5 short sentences which fooCheck() method will be executed for each of the calls and why. You may (and probably should) plug this code into a program and execute it to see what behavior it has, but your explanation must explain why static dispatch causes it to behave this way.
d. Suppose a program contains the following lines of code:
…
Foo f = new Foo("Hello world!");
Bar b = (Bar) f;
FooUtils.fooCheck(b);
FooUtils.fooCheck(f);
If you attempt to do this, Java will throw a ClassCastException at runtime on the line Bar b = (Bar) f. The code in part (c) runs without an exception, so why will this not work? Explain in 2-5 short sentences why this code cannot work. Your answer must discuss polymorphism and inheritance.
Explanation / Answer
c).
fooCheck() : method are overloaded. One take Bar's class object and second take Foo's class object
overloading is the static polymorphism (compile time polymorphism).
So all when we call oveloaded method, ot only check reference type, not actiual object.
FooUtils.fooCheck(b);
// this will call: fooCheck(Bar b) method. because 'b' is the object of Bar class.
// Output: It is a Bar!test
FooUtils.fooCheckfb);
// this will call: fooCheck(Foo f) method. because 'f' is the object of Foo class.
// Output: It is a Foo!
d)
Foo f = new Foo("Hello world!");
Bar b = (Bar) f;
We can not typecae super class Object in Child class object.
Child class reference can not hold Super class objects
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.