top of page

Objects

Tutoring > Java Coding > Objects

A class in Java is a blueprint for an object. We write a class containing field variables and methods to perform operations on values. We can then create instances of these classes called objects. We can do this by using the keyword new. The new keyword instantiates a class by allocating memory for that class and returning a reference to that memory.

 

Say we have a Car class here, with two separate constructors, one with three paramters and one without any:

 

public class Car {

String name:

String colour;

int idNumber;

 

public Car(String name, String colour, int idNumber){

this.name = name;

this.colour = colour;

this.idNumber = idNumber;

}

 

public Car(){

}

}

 

We use the new keyword in our program to create a new Car object (an instance of the class). We choose a name for the new object, here the name is "car1" but we could have chosen anything.

 

Car car1 = new Car("Mondeo", "Red", 4412);

 

Note that we use parenthesis () to call a constructor of the class we specify. If the constructor we want to use specifies any paramters then we need to include the values we want to give the variables in the parenthesis. So our instance (our object) has the name "Mondeo", the colour "Red" and the idNumber 4412.

 

We can create more than one object. For example, if you had a Car class, you might create two instances of it and give each one different attributes. The car class has a String variable called "colour", we could give the two cars different values for this colour variable. The two Cars are instances of the same class, but they can have different values for each of their variables.

 

Car car2 = new Car("Punto", "Blue", 3376);

 

Now we have two Car objects, the second one is called "car2". We can do this as many times as we need a new object.

When the object is instantiated, the constuctor invoked depending on how many parameters are specified in the parenthesis. If we wanted to create a Car object using the constructor with no parameters, we would write this:

 

Car car3 = new Car();

 

This car has no parameters and so invokes the constructor in the Car class with no parameters. You must specify a constructor with the same number of parameters as one of the constructors in the class of the object you are creating. If we tried to do this:

 

Car car4 = new Car("Fiesta", "Green");

 

it would be illegal, as no constructor has this number and type of parameters.

bottom of page