What are Objects and Classes?

  • A class defines a new data type (a classification). It is the formal implementation, or blueprint, of the attributes and behaviors of the objects of that class.
  • An object is a specific instance of a class with defined attributes. Objects are declared as variables of a class type.
  • An attribute or instance variable is data the object knows about itself. For example a turtle object knows the direction it is facing or its color.
  • A behavior or method is something that an object can do. For example a turtle object can go forward 100 pixels.

Creating and Initializing Objects: Constructors

  • Each class has constructors like World() and Turtle(habitat) which are used to initialize the attributes in a newly created object.
  • A new object is created with the new keyword followed by the class name (new Class()). When this code executes, it creates a new object of the specified class and calls a constructor, which has the same name as the class.
    • new World() creates and initializes a new object of the World class, and new Turtle(habitat) creates and initializes a new Turtle object in the World habitat.
// To create a new object and call a constructor write:
// ClassName variableName = new ClassName(parameters);
World habitat = new World();    // create a new World object
Turtle t = new Turtle(habitat); // create a new Turtle object
  • Constructors initialize the attributes in newly created objects. They have the same name as the class.
  • A constructor signature is the constructor name followed by the parameter list which is a list of the types of the parameters and the variable names used to refer to them in the constructor.
  • Overloading is when there is more than one constructor. They must differ in the number, type, or order of parameters.
  • New is a keyword that is used to create a new object of a class. The syntax is new ClassName(). It creates a new object of the specified class and calls a constructor.
  • A no-argument constructor is a constructor that doesn’t take any passed in values (arguments).
  • Parameters allow values to be passed to the constructor to initialize the newly created object’s attributes.
  • The parameter list, in the header of a constructor, is a list of the type of the value being passed and a variable name. These variables are called the formal parameters.
  • Actual parameters are the values being passed to a constructor. The formal parameters are set to a copy of the value of the actual parameters.
  • Formal parameters are the specification of the parameters in the constructor header. In Java this is a list of the type and name for each parameter (World(int width, int height).
  • Call by value means that when you pass a value to a constructor or method it passes a copy of the value.-