Answered step by step
Verified Expert Solution
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
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started