Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Q2. (10 marks] Consider the following class hierarchy. Fruit + Say Something) : void Apple Orange + makeAppleCider(): void + Say Something(): void + say

image text in transcribedimage text in transcribed

Q2. (10 marks] Consider the following class hierarchy. Fruit + Say Something) : void Apple Orange + makeAppleCider(): void + Say Something(): void + say Something's String): void + makeOrange Juice(): void + Say Something(): void Golden Delicious Mcintosh + say Something(): void + say Something's : String) void A method say Something) displays the type of object, e.g., for the Apple class, the method displays "I am an Apple". The overloaded method say Something (Strings) displays the type then the value of s, e.g., for class Apple and s="hello", the method displays "Apple says: hello!" a) What is displayed on the screen after running the code below. public class A2 { public static void main(String[] args) { Fruit[] fruits = new Fruit[5]; fruits [0] = new Fruit(); fruits[1] = new Apple(); fruits [2] = new Orange(); fruits [3] = new GoldenDelicious(); fruits[4] = new McIntosh(); for (Fruit fi: fruits) { f1.say Something(); Fruit[] apples = new Apple[3]; apples [0] = new Apple(); apples[1] = new GoldenDelicious(); apples [2] = new McIntosh(); for (Fruit f2: apples) { //add code here b) Write the missing code where indicated above in order to invoke the method say Something (String s) using the reference variable f2. Use any value for s. Explain the output (i.e., why we see each text line in the output). c) Is the following statement valid? Explain. apples [0] = new Orange(); Note about the array f2 in Q2 above: - The array is of the type Fruit. However, each element is of the type Apple. This means: the array elements can only be of the type Apple or a subtype of Apple. The reference f2 can only invoke methods known to Fruit (i.e. it cannot for example invoke methods in the Apple class if they are not defined in Fruit) We do this (array type is different from elements type) when we what to limit the programmer to use only the methods in the array type (e.g. Fruit in our example) and put a restriction on the type of objects that can be stored in the array (e.g. only Apples can be stored in f2. We cannot store oranges in the array)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design And Implementation

Authors: Edward Sciore

2nd Edition

3030338355, 978-3030338350

More Books

Students also viewed these Databases questions