In: Computer Science
java code:
Problem 1:
Create a class called Elevator that can be moved between floors in an N-storey building. Elevator uses a constructor to initialize the number of floors (N) in the building when the object is instantiated.
Elevator also has a default constructor that creates a five storey building.
The Elevator class has a termination condition that requires the elevator to be moved to the main (i.e., first) floor when the object is cleaned up. Write a finalize() method that satisfies this termination condition and verifies the condition by printing a message to the output, Elevator ending: elevator returned to the first floor.
In main(), test at least five (5) possible scenarios that can occur when Elevator is used in a building with many floors (e.g., create, move from one floor to another, etc.).
Tip: Termination occurs when the instance is set to null. You may wish to investigate “garbage collection” for this exercise.
public class Elevator extends Thread{
int floor;
public Elevator() {
// TODO Auto-generated constructor
stub
floor = 5;
}
public Elevator(int floor) {
super();
this.floor = floor;
}
public void move() {
try {
for(int
i=1;i<=floor;i++) {
System.out.println("Elevator is at floor
"+i);
sleep(1000);
}
}catch (Exception e) {
// TODO: handle
exception
}
}
public void move(int a,int b) {
System.out.println("Elevator is at
floor "+a+" and moving to floor "+b);
}
@Override
protected void finalize() throws Throwable {
// TODO Auto-generated method
stub
System.out.println("Elevator
ending: elevator returned to the first floor.");
}
public static void main(String[] args) throws
Throwable {
// TODO Auto-generated method
stub
Elevator e = new Elevator();
e.move();
e.move(5, 3);
e.finalize();
Elevator e1 = new
Elevator(10);
e1.move();
e1.move(10, 4);
e1.finalize();
}
}
Elevator is at floor 1 Elevator is at floor 2 Elevator is at floor 3 Elevator is at floor 4 Elevator is at floor 5 Elevator is at floor 5 and moving to floor 3 Elevator ending: elevator returned to the first floor. Elevator is at floor 1 Elevator is at floor 2 Elevator is at floor 3 Elevator is at floor 4 Elevator is at floor 5 Elevator is at floor 6 Elevator is at floor 7 Elevator is at floor 8 Elevator is at floor 9 Elevator is at floor 10 Elevator is at floor 10 and moving to floor 4 Elevator ending: elevator returned to the first floor.