Objects
you already know and love...
There are two kinds of data in Java: primitive types and objects. Some
examples of primitive types are int, char, boolean. We used these types to make
variables, to make arrays and as return types in methods.
An object, on the other hand is more complex than a simple variable. An
object:
·
Is Coded in a Class.
Whenever you write ‘public class x’ you are making the template for an
object of type x. An example of a class we use to make objects is the Button
class.
·
Has Instance variables.
These are the data stored in the object. The Buttons we have already used had
variables to store their font, their labels and their colour.
·
Has Methods.
These are the things that you can do to the object and that the object can to
for you. The methods we used on Buttons were setLabel, setFont, etc.
·
Has a Constructor:
There are special methods that are called the same thing as the class. They are
used to set up the object’s space in memory. You called the Button’s
constructor with the keyword new:
Button exit; //declaring a button object
Exit = new Button (“EXIT”); //calling the constructor with new.
Questions
1.
Consider a Label.
(a)
What is a Label’s class name?
(b)
What are some of the things a Label might store in its instance variables?
(c)
What are some of the methods we used with a Label?
(d)
Declare two Label objects. Call one object James and the other object Gosling.
(e) Construct both Label objects. Leave James blank,
but make Gosling read “I love Java”.
2.
Consider a TextField.
(a)
What is a TextField’s class name?
(b)
What are some of the things a TextField might store in its instance variables?
(c)
What are some of the methods we used with a TextField?
(d)
Declare two TextField objects. Call one object Dennis and the other object
Ritchie.
(e)
Construct both Label objects. Make Dennis 15 characters long, and make Ritchie
read “I love C++”.
3.
Why don’t primitive types have constructors?
4.
Could an object contain a variable of a primitive type? Could a primitive type
contain an object? Explain.
5. Name 3 other objects we have used already. Pick out some of their
instance variables and their methods.