Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

java question 6 The following classes have been created. public class Plate { public void method1() { System.out.println(Plate); } } class Fork { public void

java

question 6

The following classes have been created.

public class Plate { public void method1() { System.out.println("Plate"); } } class Fork { public void method2() { System.out.println("Fork"); } } class Spoon { public void method3() { System.out.println("Spoon"); } }

The following driver has been created but it does not compile. what is the cause of the error and how can you fix it.

class Driver { public static void main(String[] args) { Object[] stuff = {new Spoon(), new Fork(), new Plate()}; for(int i = 0; i < stuff.length; i++) { stuff[i].method1(); Stuff[i].method2(); stuff[i].method3(); } } }

solution: since there is an array of Objects, every element in the array must be type casted to the proper type. then the method from the class can be called on it.

class Driver { public static void main(String[] args) { Object[] stuff = {new Spoon(), new Fork(), new Plate()}; for(int i = 0; i < stuff.length; i++) { if(stuff[i] instanceof Plate) { Plate p = (Plate)stuff[i]; p.method1(); } else if(stuff[i] instanceof Fork) { Fork f = (Fork)stuff[i]; f.method2(); } else if(stuff[i] instanceof Spoon) { Spoon s = (Spoon)stuff[i]; s.method3(); } } } }

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

Graph Databases In Action

Authors: Dave Bechberger, Josh Perryman

1st Edition

1617296376, 978-1617296376

More Books

Students also viewed these Databases questions

Question

Differentiate 3sin(9x+2x)

Answered: 1 week ago

Question

What are the Five Phases of SDLC? Explain each briefly.

Answered: 1 week ago

Question

How can Change Control Procedures manage Project Creep?

Answered: 1 week ago