Question

Status Topic Interfaces Description Video Scene Problem Consider a video scene in which we want to...

Status

Topic

Interfaces

Description

Video Scene Problem

Consider a video scene in which we want to display several different types (classes) of objects. Let's say, we want to display three objects of type Deer, two objects of type Tree and one object of type Hill. Each of them contains a method called display. We would like to store their object references in a single array and then call their method display one by one in a loop. However, in Java, we cannot have an array in which we can store different type of object references. (In Java, if we create an array of type Deer, we can store in it only Deer references and if we create an array of type Tree, we can store in it only Tree references and so on.) We will encounter the same problem in our assignment below. How do we solve this problem?

Assignment Problem

In our assignment (see the Assignment Description later below), we would like to create three Rectangle objects, two Sibling objects and one Student object. We would like to provide methods displayStatus and getStatus in each of these objects. We would like to store the references of these objects in a single array. Then, in a loop, we would like to call the methods displayStatus (or getStatus) of each of these objects one by one. In the code fragment below, we attempt to do just that.

for (int i=0; i<6; i++) {

            objectArray [i].displayStatus();

}

Normally, the above is not possible in Java because we cannot store objects of different types in a single array. We will solve this problem below using interfaces.

Using an Interface

We will solve the above problem by creating an interface Status in which we will declare two methods displayStatus and getStatus by providing their headers as shown below.

//File: Status.java

public interface Status

{

            public void displayStatus ( );

            public String getStatus ( );

}

Then we will implement the interface Status in each of the three classes Rectangle, Sibling and Student. This will require us to provide methods displayStatus and getStatus in each of the above three classes. The contents of these methods will be different in each class. Implementing the interface Status in each of the above classes will have the following benefit: it will make the objects of these classes to be of type Status in addition to their original class types. In other words, the objects of these three different class types, will also become the objects of a one common type, namely Status. Thus we will be able to store their reference in a single array of type Status.

We will create an array of type Status of size 6 as below.

Status[] status = new Status[6];

Note that status above is an array of six references of type Status. It can store six Status references. We will store in it three Rectangle object references, two Sibling object references and one Student object reference. We will be able to do that, because each of the Rectangle, Sibling and Student references is of type Status in addition to its original class type. Also, we will be able to call their method displayStatus or getStatus in a loop as below:

for (int i=0; i<6; i++) {

            status [i].displayStatus(); //Polymorphic call

}

Polymorphism and Dynamic Method Binding

  

Poly means 'multiple' and morph means 'form'. So, polymorphism implies multiple forms. Since, above array status contains references to objects of three different class types, we can call this array a polymorphic array. Also, above, we are calling the method displayStatus on objects of three different class types, so we can refer to this method call a polymorphic call.

In Java, in general, method calls are not statically bound i.e. the compiler does not determine their jump addresses. Instead, their jump addresses are determined at run-time i.e. they are bound at runtime. Their binding is called dynamic binding or delayed binding. For example, for a method call such as status[i].displayStatus above, Java determines the jump address of displayStatus at run time during each call of the method in a loop. Within the loop, if the method call is to a Rectangle object because status[i] is Rectangle reference type, it jumps to the Rectangle's displayStatus method. if the method call is to a Sibling object because status[i] is Sibling reference type, it jumps to the Sibling's displayStatus methIf status[i] and so on.

In brief, a call to displayStatus method above in a loop, results in calling different displayStatus methods because method binding in Java is done at runtime. Hence, polymorphism is possible only in languages that provide dynamic method binding.

Assignment Description

Purpose

The purpose of the exercise is to provide a set of common methods in different type of objects and then (polymorphically) call those method on these objects in a loop. Specifically, in this assignment, you will provide two common methods, displayStatus and getStatus, in three Rectangle, two Sibling and one Student objects and (polymorphically) call these methods in a loop.

Steps

For doing this assignment, follow the steps below: (For details, refer to the Implementation section)

1.     Create classes Rectangle, Sibling and Student or copy them from previous assignments.

2.     Create an interface Status containing the headers of the methods displayStatus [public void displayStatus();] and getStatus [public String getStatus();]

3.     Implementing the interface Status in each of the three classes: Rectangle, Sibling and Student. This would require you to add methods displayStatus and getStatus in each of these classes.

4.     Create an array of type Status of size 6. (You will be able to create an array of type Status because you are just creating an array of references of type Status. It is not possible to create objects of type Status because it is an interface.)

5.     Create three objects of class Rectangle, two of class Siblings, one of class Student and store their references in the above array of type Status. (Having implemented the interface Status, objects of these classes are of type Status in addition to their original types.)

6.     In a loop, call the method displayStatus on each object. (Each will display its status.)

7.     In a loop, call the method getStatus on each object. (Each will return its status as a String.)

8.     Accumulate, in String variable out, the statuses returned from the above method calls.

9.     Display the content of string variable out in a dialog box.

Implmentation

Create an interface Status containing the following method:

public void displayStatus ( );

public String getStatus ( );

Create a class Rectangle containing two private instance variables double length and double width. Provide a two-parameter constructor that will initialize the two instance variables. Implement the interface Status.

Create a class Sibling containing three private instance variables: String name, int age and int weight. Provide a three-parameter constructor that will initialize the three instance variables. Implement the interface Status.

Create a class Student containing three private instance variables: int id, String name and double array scores. Provide a three-parameter constructor that will initialize the three instance variables. Implement the interface Status.

In each of the above classes, implement the interface Status. For this purpose, do the following:

·           In the class header, add the phrase: implements Status

          (When you hover the cursor over the header line after entering the above phrase, Eclipse will show a pop-up menu. You can select implement methods and Eclipse will automatically generate the template of the two methods: getStatus and displayStatus. Then, you can fill in the code for the two methods as below)

·           Add the method getStatus ( ) in the body of the class

          (or let Eclipse generate the template automatically as mentioned earlier above)

This method returns the status as a String. The string returned includes:

The name of the class on one line.

The name of all instance variables along with their values on a second line.

For example, for an object of class Rectangle of length 3 and width 2, the String returned should be as below:

“Rectangle\nLength=3, Width=2\n”

·           Add the method displayStatus ( ) in the body of the class

         (or let Eclipse generate the template automatically as mentioned earlier above)

This method will call the method getStatus and display the status received

  

Create a class TestStatus containing the method main ( ). In the main method do the following:

·           Create an array stat of size 6 for Status references. (Compiler allows you to create such an array). This array will be populated with references of different objects later.)         

·           Create three Rectangle objects, initialize them with data values provided by the user and store their references in the first 3 elements of the Status array. (You can do this because the class Rectangle implements the interface Status and thus a Rectangle object is both of type Rectangle and Status).

·           Create two Sibling objects, initialize them with data values provided by the user and store their references in the next two elements of the Status array. (You can do this because the class Sibling implements the interface Status and thus a Sibling object is both of type Sibling and Status).

·           Create one Student objects, initialize it with data values provided by the user and store its reference in the next one element of the Status array. (You can do this because the class Student implements the interface Status and thus a Student object is both of type Student and Status).

·           Set up a loop to iterate through the array of Status references. (Each reference in the Status array will point to an object). During each pass through the loop, call method displayStatus on a Status reference and it will display its status.

·           Set up a loop to iterate through the array of Status references. (Each reference in the Status array will point to an object).

During each pass through the loop,

Call the method getStatus ( ) to get the Status of each object as a String, and accumulate the output into a String variable out.

·       On exit from the loop, display the content of variable out in a dialog box..

Testing

For input/output, you may use JOptionPane.showInputDialog

.

Input

Data for three Rectangle objects:

3 2

6 4

30 20

Data for two Sibling objects:

Jack 21 130

Judy 24 118

Data for one Student Object:

1,John Adam,3,93,91,100

Output

The output should show the status of each of the object one after the other as below.

Rectangle

length=3, width=2

Rectangle

length=6, width=4

Rectangle

length=30, width=20

Sibling

name=Jack, age=21, weight=130

Sibling

name=Judy, age=24, weight=118

Student

id=1, name=John Adam, scores=93, 91, 100

Submit

Copy the following in a file and submit the file:

Final dialog box containing the output of all the six objects in a single dialog box

Source code of the interface and all the classes

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution:-

//Java Code

public interface Status {
public void displayStatus();
public String getStatus();
}

//=====================================

import javax.swing.*;

public class Rectangle implements Status {
private double width;
private double length;

//constructor

public Rectangle(double width, double length) {
this.width = width;
this.length = length;
}
//getters

public double getWidth() {
return width;
}

public double getLength() {
return length;
}

@Override
public void displayStatus() {
JOptionPane.showMessageDialog(null,getStatus());
}

@Override
public String getStatus() {
return "Rectangle\nLength="+length+", Width="+width+"\n";

}
}

//==================================================

import javax.swing.*;

public class Sibling implements Status {
private String name;
private int age;
private int weight;
//constructor

public Sibling(String name, int age, int weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
//getters

public String getName() {
return name;
}

public int getAge() {
return age;
}

public int getWeight() {
return weight;
}

@Override
public void displayStatus() {
JOptionPane.showMessageDialog(null,getStatus());
}

@Override
public String getStatus() {
return "Sibling\nName="+name+", Age="+age+", Weight="+weight+"\n";
}
}

//====================================================

import javax.swing.*;

public class Student implements Status {
private int id;
private String name;
private double[] scores;

//constructor

public Student(int id, String name, double[] scores) {
this.id = id;
this.name = name;
this.scores = scores;
}
//getters

public int getId() {
return id;
}

public String getName() {
return name;
}

public String getScores() {
StringBuilder result = new StringBuilder();
for (int i = 0; i result.append(scores[i]);
if(i result.append(", ");
}
return result.toString().toString();
}

@Override
public void displayStatus() {
JOptionPane.showMessageDialog(null,getStatus());
}

@Override
public String getStatus() {
return "Student\nid="+id+", name="+name+", scores="+getScores()+"\n";
}
}

//==============================================

import javax.swing.*;
import java.awt.*;

public class TestStatus {
public static void main(String[] args)
{
String in;
StringBuilder out= new StringBuilder();
//create an array of status
Status[] status = new Status[6];
//status index
int statusIndex=0;
//Create three Rectangle objects
for (int i = 0; i <3 ; i++) {
in = JOptionPane.showInputDialog("Enter Length: ");
double length = Double.parseDouble(in);
in = JOptionPane.showInputDialog("Enter width");
double width = Double.parseDouble(in);
//Create Rectangle
status[statusIndex] = new Rectangle(width,length);
statusIndex++;
}

//Create two sibling objects
for (int i = statusIndex; i < status.length-1; i++) {
in = JOptionPane.showInputDialog("Enter name: ");
String name = in;
in = JOptionPane.showInputDialog("Enter age: ");
int age = Integer.parseInt(in);
in = JOptionPane.showInputDialog("Enter Weight: ");
int weight = Integer.parseInt(in);
//Create Sibling object
status[statusIndex] = new Sibling(name,age,weight);
statusIndex++;
}

//Create one Student object
in = JOptionPane.showInputDialog("Enter id: ");
int id = Integer.parseInt(in);
in = JOptionPane.showInputDialog("Enter name: ");
String name = in;
in = JOptionPane.showInputDialog("How many scores: ");
int size = Integer.parseInt(in);
double[] scores =new double[size];
for (int i = 0; i in = JOptionPane.showInputDialog("Enter score"+(i+1)+": ");
scores[i]= Integer.parseInt(in);
}
//Create Student object
status[statusIndex]= new Student(id,name,scores);
statusIndex++;

//create for loop to display all status
for (Status s:status
) {
s.displayStatus();
out.append(s.getStatus());
}
//Display output in single dialog box
JOptionPane.showMessageDialog(null,out.toString(),"STATUS",JOptionPane.INFORMATION_MESSAGE);
}
}

//Output

STATUS X i Rectangle Length=3.0, Width=2.0 Rectangle Length=6.0, Width=4.0 Rectangle Length=30.0, Width=20.0 Sibling Name=jac

Note:- If you need any help regarding this solution........ please leave a comment....... thanks

Add a comment
Know the answer?
Add Answer to:
Status Topic Interfaces Description Video Scene Problem Consider a video scene in which we want to...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (The interface class-like) Assume you have the Edible interface with its abstract method. Design a class named Animal a...

    (The interface class-like) Assume you have the Edible interface with its abstract method. Design a class named Animal and its two subclasses named Mammal and Dairy. Make Sheep and Bear as subclasses of Mammal and make implement the Edible interface. howToEat() and sound() are the main two methods for all edible classes while sound() is the main method for the non-edible classes. 1. Draw the UML diagram for the classes and the interface 2. Use Arraylist class to create an...

  • Java Description Write a program to compute bonuses earned this year by employees in an organization....

    Java Description Write a program to compute bonuses earned this year by employees in an organization. There are three types of employees: workers, managers and executives. Each type of employee is represented by a class. The classes are named Worker, Manager and Executive and are described below in the implementation section. You are to compute and display bonuses for all the employees in the organization using a single polymorphic loop. This will be done by creating an abstract class Employee...

  • Exercise 8 (The interface class-like) Assume you have the Edible interface with its abstract method Design...

    Exercise 8 (The interface class-like) Assume you have the Edible interface with its abstract method Design a class named Animal and its two subclasses named Mammal and Dairy. Make Sheep and Bear as subclasses of Mammal and make Chicken and Cow as subclasses of Dairy. The Sheep and Dairy classes implement the Edible interface. howToEat) and sound() are the main two methods for all edible classes while sound() is the main method for the non-edible classes. 1. Draw the UML...

  • Q2) Interface Create a program that calculates the perimeter and the area of any given 2D...

    Q2) Interface Create a program that calculates the perimeter and the area of any given 2D shape. The program should dynamically assign the appropriate calculation for the given shape. The type of shapes are the following: • Quadrilateral 0 Square . Perimeter: 4xL • Area:LXL O Rectangle • Perimeter: 2(L+W) • Area:LxW Circle Circumference: I x Diameter (TT = 3.14) Area: (TT xD')/4 Triangle (assume right triangle) o Perimeter: a+b+c O Area: 0.5 x base x height (hint: the base...

  • C++ ONLY PLEASE Problem Description: Objective: Create Inheritance Hierarchy to Demonstrate Polymorphic Behavior Create a Rectangle...

    C++ ONLY PLEASE Problem Description: Objective: Create Inheritance Hierarchy to Demonstrate Polymorphic Behavior Create a Rectangle Class Derive a Square Class from the Rectangle Class Derive a Right Triangle Class from the Rectangle Class Create a Circle Class Create a Sphere Class Create a Prism Class Define any other classes necessary to implement a solution Define a Program Driver Class for Demonstration a) Create a Container to hold objects of the types described above b) Create and Add two(2) objects...

  • Java Project In Brief... For this Java project, you will create a Java program for a...

    Java Project In Brief... For this Java project, you will create a Java program for a school. The purpose is to create a report containing one or more classrooms. For each classroom, the report will contain: I need a code that works, runs and the packages are working as well The room number of the classroom. The teacher and the subject assigned to the classroom. A list of students assigned to the classroom including their student id and final grade....

  • Implement an abstract class named Person and two subclasses named Student and Staff in Java. A person has a name, address, phone number and e-mail address. A student has a credit hour status (freshman...

    Implement an abstract class named Person and two subclasses named Student and Staff in Java. A person has a name, address, phone number and e-mail address. A student has a credit hour status (freshman, sophomore, junior, or senior). Define the possible status values using an enum. Staff has an office, salaray, and date-hired. Implement the above classes in Java. Provide Constructors for classes to initialize private variables. Getters and setters should only be provided if needed. Override the toString() method...

  • CIS4100 Final Project Description The Objective of this Final Project is to implement the theoretical concepts...

    CIS4100 Final Project Description The Objective of this Final Project is to implement the theoretical concepts covered in the course. You are required to build the classes and test all the functions as described. Each class should have its own .h (specification) and .cpp (implementation) files, then test all the classes in the main.cpp The Diagram below shows the classes inheritance relationships: The assigned Types are as follow: Type 1 Type 2 Type 3           PitBull Lion Tiger The class...

  • ********************Java Assigment******************************* 1. The following interface and classes have to do with the storage of information...

    ********************Java Assigment******************************* 1. The following interface and classes have to do with the storage of information that may appear on a mailing label. Design and implement each of the described classes below. public interface AddrLabelInterface { String getAttnName(); String getTitle(); // Mr., Mrs., etc. String getName(); String getNameSuffix(); // e.g., Jr., III String getProfessionalSuffix(); // O.D. (doctor of optometry) String getStreet(); String getSuiteNum(); String getCity(); String getState(); String getZipCode(); } Step 1 Create an abstract AddrLabel class that implements the...

  • pls help java ASAP!!!!!!! Topic String Tokenizer Static Methods Static Variables Primitive Arrays Description Enhance the...

    pls help java ASAP!!!!!!! Topic String Tokenizer Static Methods Static Variables Primitive Arrays Description Enhance the last assignment by providing the following additional features: (The additional features are listed in bold below) Class Statistics In the class Statistics, create the following static methods (in addition to the instance methods already provided). • A public static method for computing sorted data. • A public static method for computing min value. • A public static method for computing max value. • A...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT