What is an object?

  • An object is a representation of a real-world entity e.g. teacher, aeroplane, mobile phone, cat etc
  • A class is like a blueprint that describes the properties and behaviours of objects, while an object is a specific instance created based on that blueprint with its own unique values for the properties
  • A constructor is a special method within a class that is automatically called when an object of that class is created (instantiated)
  • Constructors typically define the initial values of instance variables and perform any necessary setup to prepare the object for use

Example of 2 objects belonging to a class Example of 2 objects belonging to a class

Worked Example

A supermarket uses an object-oriented approach to organise items that it offers for sale. Part of the class definition for the ItemForSale class is shown below:

class ItemForSale public itemName public price public discount

Write a line of code to create an object of type ItemForSale called mushypeas that has a name of “mushy peas” and a price of £0.89

[3]

How to answer this question:

  • Creating object with identifier
    • mushypeas =
  • creating object as type
    • ItemForSale
  • mark for parameters passed in as needed (“mushy peas”,0.89) [1 mark]

Answer:

Example answer 1 to get full marks:

mushypeas=new ItemForSale("mushy peas", 0.89)

Example answer 2 to get full marks:

ItemForSale mushypeas = ItemForSale(“mushy peas”,0.89);