Question: 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!