objects and constructors

Download Report

Transcript objects and constructors

More about Java Classes
Writing your own Java Classes
More about constructors and
creating objects
Java Objects



We can define our own types using the
Java keyword class
Your understanding and use of
Classes/objects is fundamental to
getting to grips with Java
It is also the biggest climb on the
learning curve - so be patient
What are Java Classes?



Classes are templates
They encapsulate data (variables) and
behaviour (methods)
Variables can either be primitive (int,
char etc) or reference types (String etc)
Classes and Objects –
there is a difference





An object is an occurrence (or instance) of a
Class
The Class describes the blueprint or template
An object is made from a class
For an Employee class, each employee would
be an object with the data and method
structure of the class
Although the structure is the same for all
objects built from this class, the values held
within the data can be different
How to Create objects
from a class?
The new keyword is used to create an
instance of a class - an object reference
Employee JonWestlake = new Employee( );
 new is the ONLY way to create objects**
See examples
Employee1.java - a single class with one object
Employee2.java - a single class with two objects
Employee3.java - a single class with many
objects

What does that new
statement mean?
Employee JonWestlake = new Employee( );


Declares a “reference variable” of type
Employee
So JonWestlake does have a memory location
but no “pointer” to an object yet - essentially
a null object
Breakdown of new statement

Right hand side
= new Employee( );


Creates an object of the Employee class
We could have done the statements in two
stages;
Employee JonWestlake;
JonWestlake = new Employee( );
What is an object reference?

Think of a reference as a name for an object
- JonWestlake is the name of a an Employee
object
Employee JonWestlake = new Employee( );

reference names can be meaningful as in this
case or as we can see with the Employee
application
Object references

It is legal for two references (or more) to refer
to the same object e.g. in the Employee example
we might wish to refer to the object via some
initials as well
Employee JonWestlake = new Employee( );
Employee jcw = JonWestlake;

jcw refers to the same Employee as JonWestlake
What does new do? - memory




new takes the memory it needs to create an
object from a special memory pool that Java
controls automatically, called the heap
All class objects in Java come from the heap
Java allocates enough memory to hold the
object
Java allocates memory for objects when the
object is created, not at application start up
What does new do? - constructor



Java initialises any instance variables to
default values - default constructor
Java makes calls to any constructors that
exist for that class
So, what is a constructor?
Content of Constructors





Constructors are a “special” method used to
initialise an object created for a class
The name is the same as the class, so starts
with a capital letter
Constructor can do anything a normal
method can do**
No return type - not even void
The constructor does not contain a return
statement
Content of Constructor

Like any method a constructor can include
arguments. These arguments indicate to the
constructor how to set up the initial values for
the data fields of an object
See Employee2 for example
What happens if we don’t use
a Constructor?



Every class has a single default constructor
with no parameters
The default constructor takes no arguments
and does nothing other than initialize all
object variables to their zero or null state
As soon as the developer defines a
constructor then the default constructor is no
longer used
What should a Constructor do?




Creating objects to a valid starting state
according to content of the constructor and
arguments passed into the constructor
they are usually used to simply initialize
variables within the object to some starting
value
or they could be used to add objects to a
linked list
or increment an object count…
What should the Constructor do?


We advise you not to place instance
style functionality within the constructor
Use the constructor to initialize an
instance - keeps it simple and
maintainable!
Overloading the Constructor




A class is free to have more than one
constructor
The constructors must have different
argument signatures
Often one “root” constructor has all the
program logic for construction
Other constructors set a few defaults
and then call the root constructor
Example Overloaded Constructor
Item(String itemDesc)
{ Item(itemDesc, 0);
}
Item(String itemDesc, int itemWght)
{ description = itemDesc;
weight = itemWght;
}
new operator for Item class

The first example of the constructor sets the item
weight to 0 and passes this information on to the
full constructor
Item defaultItem = new Item(“General Stock”);

Alternatively, you could call the second
constructor directly
Item specifyItem = new Item(“Widgets”, 50);
Overloading Constructors - Tips



Place all the initialisation code in a root
constructor
Root constructor is usually the constructor
with the most parameters
define “convenience” constructors with fewer
parameters - these constructors call the root
constructor using default values for the
parameters which the user has not provided
See Employee5.java example
Using a test to drive
the choice of constructor


We can ask the user something
Based on the user input, we can test the
input and select the constructor appropriate
to the input
See VideoEx1.java or Employee5.java
Invoking one
Constructor from another




One constructor can invoke another
constructor of the same class using the this
keyword
this - a special (pseudo) variable
pseudo means the value is changed by the
system not the developer
a reference to the object within which a
constructor is executing
useful as it enables messages to “this” the
current object to be performed - see
VideoEx2.java
Running the Constructor


Constructors do not have an explicit
keyword to mark them as such and they
cannot be called like a normal method
see Employee1, Employee2 and
Employee3
Where to position the constructor?



Position the constructor either before the
main method (if there is one for the class) or
after the main method
see the examples
Each constructor is defined separately i.e. not
nested
Constructor access modifiers



The access modifiers are exactly the same as
for classes - public or nothing**
Modifier must be public if classes outside of
the current package need to be able to use
the object being defined - design issue
if public is not used then constructor is only
available within the package to which the
class belongs - for our work this is usually the
case
Destructors!



There is NO destructor in Java
In C++ a destructor is used to return
memory to heap of available memory
Java manages memory automatically
via the constructor and automatically
returns memory when objects are
abandoned
Summary


We have looked further at classes
 We have investigated the role of the constructor
Practical – get the examples running and write
your own versions!