
Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The relationship between superclasses and subclasses in java, focusing on inheritance and polymorphism through the example of classes a and c. It covers the concept of type rules, method overriding, and the execution of tostring() method.
Typology: Assignments
1 / 1
This page cannot be seen from the preview
Don't miss anything!

Assume that statement below compile and runs without errors:
A data = new C();
A data = new C();
For the following interaction answer yes or no if the code compiles with error. If it compiles does it have run-time/semantic errors. Explain.
((C)data).c();
Compiles. Without the cast it would be compile error as c() is not in class A and variable data is of type A. It also executes without errors as variable data is referring to an instance of C.
((B)data).b();
Compiles. Without the cast it would be compile error as b() is not in A and variable data is of type A. However, it does not execute as variable data is referring to an instance of C. We cannot convert an instance of type C to a B.
A data = new C(); Consider the execution data //or can also do data.toString()
From which class is the toString method executed?
From class C. Variable data is referring to object of type C. Due to overriding, java picks the method lowest in the inheritance chain. If toString( ) was not in class C, then the method written in class A would be executed by object of type C as it would inherit the method from class A. If both A and C did not have toString() method, then method from Object class would be executed (parent of all) and whose default behavior is to return’s objects heap address.