Sie sind auf Seite 1von 2

David Sowerbutts a1192943 3rd Tute

QUESTION 1:

1. In a Java program, what happens when an object is instantiated?


2. Which reserved word is used to instantiate an object?
3. Are there any kinds of objects that can be instantiated without using the reserved
word of part (2)?

1. When an object is instantiated it is stored to memory as a new object.


2. The reserved word used for instantiation is ‘new’. Ex. Bankaccount = new
bankaccount(initalbalance).
3. Only String objects can be instantiated without using the operator ‘new’.

QUESTION 2:

1. Explain the difference between an object and an object reference?


2. Explain the difference between an object and a class?

1. Each new object is located in a separate space of memory. Instead of creating a


new object, an object reference calls on the previously created object.
2. A class is a model for an object. An object is higher than a class. A class defines
what the object can do.

QUESTION 3:

Give Java code to construct the following objects:


* A rectangle with center (100, 100) and all side lengths equal to 50.
* A string "Hello, Dave!"
Create objects, not object variables.

Rectangle object
Java.util.Rectangle rectangle = new java.util.Rectangle(100, 100, 50, 50)

String:
String greet = (“Hello, Dave!”)
QUESTION 4:

Write a program RandomTester that uses a Random Number generator to print out
5 randomly generated integer numbers between 1 and 6 (perhaps simulating dice
rolls). Your code should use a single random number generator (Random) object.
What test(s) could you write to ensure that your program behaved correctly?

public class RandomTester


{

public static void main(String[] args)


{
int count = 0;
int num = 0;
while (count < 5)
{
java.util.Random gen = new java.util.Random();
num = gen.nextInt(4);
System.out.print(num+2+" ");
count++;
}

}
}

To test this program I just ran it several times to see what values it would come up with.

QUESTION 5

Find the errors in the following statements:


* Rectangle r = (5, 10, 15, 20);
Error: The class of the object has not been defined in the correct syntax.
* double width = Rectangle(5, 10, 15, 20).getWidth();
Error: a rectangle object has not yet been created, thus the width cannot be found.
* Rectangle r;
r.translate(15, 25);
Error: The rectangle, r has not been properly defined as a Rectangle object.
* r = new Rectangle();
r.translate("far, far away!");
Error: Rectangle has no parameters. Must have parameters describing the size and
position. The parameters of the method, translate, must be in the form int x, int y. “far, far
away!” is a string, not an integer set.

Das könnte Ihnen auch gefallen