Question

In: Computer Science

Programming Language : JAVA Create an interface named Turner, with a single method called turn(). Then...

Programming Language : JAVA

Create an interface named Turner, with a single method called turn(). Then create 4 classes:

1- Leaf: that implements turn(), which changes the color of the Leaf object and returns true. If for any reason it is unable to change color, it should return false (you can come up with a reason for failure). The new color can be determined at random.

2- Document: that implements turn(), which changes the page on the document to the next page and returns true. If the current page is the last page of the document, then it returns false. This class should have a method called returnIdDate(), which returns a String containing the ID of the Document and the date it was published.

3- Pancake: that implements turn(), which flips the pancake if it has not flipped before and returns true. If the pancake has already been flipped, then it returns false.

4- Think of one more objects that can use turn(). Create the class and implement the turn() method. Show your creativity.

Write an application, DemoTurners, which:

  1. Creates an array of 4 Turner objects and adds one object for each of the 4 class types to it.
  2. Demonstrates polymorphism by calling the turn() method on each object in a loop.
  3. Prints the Document object’s returnIdDate method using the Turner object (how can this be done?)

Solutions

Expert Solution

Interface allows us to add polymorphism into our code. An interface defines a template for a class. Then any class which implements it, need to add the implementation for the template methods, in this case it is turn().

Java Code:

Interface:

interface Turner {
    public boolean turn();
}

Classes which implement this interface:

Pancake Class

class Pancake implements Turner{
    //to store the status of pancake
    boolean isFlipped = false;
    public boolean turn(){
        //do not turn if isFlipped is true
        if (!isFlipped)
        isFlipped = true;
        else return false;
        return true;
    }
}

Document Class:

class Document implements Turner{
    //current and last page values
    int lastPage = 20;
    int currentPage = 0;
    public boolean turn(){
        //if on last page, do not turn
        if (currentPage==lastPage)
        return false;
        currentPage = currentPage + 1;
        return true;
    }
    String returnIdDate(){
        //returning the required string
        return "Document ID: IS2165\nPublishing Date: 23rd September, 2019";
    }
}

Leaf Class:

class Leaf implements Turner{
    // store color list
    String colorsList[] = {"White","Green","Yellow","Pink"};
    String color;
    public boolean turn() {
        //generate random number using Math.random
        // it returns double value between 0 and 1, so we convert it into integer
        int randomNo = (int) (Math.random()*10);
        if (randomNo<=3)
        this.color = colorsList[randomNo];
        else return false;
        return true;
    }
}

Chair Class (One extra class that needs to be created):

class Chair implements Turner{
    boolean isFlipped = false;
    public boolean turn(){
        //set the new state opposite to current
        isFlipped = !isFlipped;
        return true;
    }
}

DemoTurner class to test the above classes:

import java.util.ArrayList;
public class DemoTurner{
    public static void main(String[] args) {
        //list of generic type
        ArrayList<Turner> demoTurner = new ArrayList<Turner>();
        //adding the objects
        demoTurner.add(new Chair());
        demoTurner.add(new Pancake());
        demoTurner.add(new Leaf());
        demoTurner.add(new Document());
        //traversing the list to invoke turn() for every object
        for (int i = 0; i < demoTurner.size(); i++) {
            System.out.println(demoTurner.get(i).turn()); 
        }
        //invoking special method of Document class
        System.out.println(((Document)demoTurner.get(3)).returnIdDate());
    }
}

Reference screenshots:

Output of the program:

In the for loop we simply write demoTurner.get(i).turn() and it automatically runs the respective method implementation of each class. This is because this method has been declared in interface.

To call the special method of Document class, we first get the object from demoList and then type cast it to Document type. After this we can call such methods.


Related Solutions

Java Programming Create a class named Problem1, and create a main method, the program does the...
Java Programming Create a class named Problem1, and create a main method, the program does the following: - Prompt the user to enter a String named str. - Prompt the user to enter a character named ch. - The program finds the index of the first occurrence of the character ch in str and print it in the format shown below. - If the character ch is found in more than one index in the String str, the program prints...
In Java Create an interface Create an interface Printing, which have a method getPageNumber () that...
In Java Create an interface Create an interface Printing, which have a method getPageNumber () that return page number of any printing. Create an abstract class named Novel that implements Printing. Include a String field for the novel's title and a double field for the novel price. Within the class, include a constructor that requires the novel title, and add two get methods--one that returns the title and one that returns the price. Include an abstract method named setPrice().. Create...
Answer the following in Java programming language Create a Java Program that will import a file...
Answer the following in Java programming language Create a Java Program that will import a file of contacts (contacts.txt) into a database (Just their first name and 10-digit phone number). The database should use the following class to represent each entry: public class contact {    String firstName;    String phoneNum; } Furthermore, your program should have two classes. (1) DatabaseDirectory.java:    This class should declare ArrayList as a private datafield to store objects into the database (theDatabase) with the...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class,...
JAVA PROGRAMMING. In this assignment, you are to create a class named Payroll. In the class, you are to have the following data members: name: String (5 pts) id: String   (5 pts) hours: int   (5 pts) rate: double (5 pts) private members (5 pts) You are to create no-arg and parameterized constructors and the appropriate setters(accessors) and getters (mutators). (20 pts) The class definition should also handle the following exceptions: An employee name should not be empty, otherwise an exception...
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A...
THIS IS JAVA PROGRAMMING 1. Create a class named Name that contains the following: • A private String to represent the first name. • A private String to represent the last name. • A public constructor that accepts two values and assigns them to the above properties. • Public methods named getProperty (e.g. getFirstName) to return the value of the property. • Public methods named setProperty ( e.g. setFirstName)to assign values to each property by using a single argument passed...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a...
PROGRAMMING LANGUAGE : JAVA Problem specification. In this assignment, you will create a simulation for a CPU scheduler. The number of CPU’s and the list of processes and their info will be read from a text file. The output, of your simulator will display the execution of the processes on the different available CPU’s. The simulator should also display: -   The given info of each process -   CPU utilization - The average wait time - Turnaround time for each process...
Programming language is Java: Write a pseudocode method to determine if a set of parentheses and...
Programming language is Java: Write a pseudocode method to determine if a set of parentheses and brackets is balanced. For example, such a method should return true for the string, "[()]{}{[()()]()}" and false for the string "[(])". Also please discuss how the algorithm will perform and how much space in memory it will take if somebody passes a massive string as input.
Java program Create a public method named saveData for a class named Signal that will hold...
Java program Create a public method named saveData for a class named Signal that will hold digitized acceleration data. Signal has the following field declarations private     double timeStep;               // time between each data point     int numberOfPoints;          // number of data samples in array     double [] acceleration = new double [1000];          // acceleration data     double [] velocity = new double [1000];        // calculated velocity data     double [] displacement = new double [1000];        // calculated disp...
(The Colorable interface) Design an interface named Colorable with a void method named howToColor(). Every class...
(The Colorable interface) Design an interface named Colorable with a void method named howToColor(). Every class of a colorable object must implement the Colorable interface. Design a class named Square that extends GeometricObject and implements Colorable. Design another class named Triangle that extends GeometricObject and implements Colorable. Implement howToColor in Square to display the message Color all four sides. Implement howToColor in Triangle to display the message Color all three sides. Draw a UML diagram that involves Colorable, Square, Triangle,...
JAVA Given the company and Employee interface, create a findLeastPaid() method (that will do the opposite...
JAVA Given the company and Employee interface, create a findLeastPaid() method (that will do the opposite of whats below). instead of finding the the best paid convert it find the lowest paid person. Given the Company and FullTimeEmployee classes and the Employee interface, write a Java program that reads in a file of full time employees with each line of input containing the name of the employee (String) and gross Salary (double) and stores them in an array list. Then...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT