You are on page 1of 14

CS 1301 – COMPUTER SCIENCE I

Storing the state – data members;


Constructing an object - constructors
Last class
◦ Organization of a project
◦ Method declarations
◦ Specification
◦ Pre and postconditions
◦ Header
◦ Body
◦ Syntax errors
Today
◦ Storing state – data members
◦ Constructing an object
◦ Constructors
Object-oriented
programming
◦ Design, development and use of objects to develop
software applications.

◦ Object
◦ State – characteristics, attributes
◦ Behavior – what you can tell it to do, what you can
ask it

◦ Example
◦ Student
◦ BankAccount
Object vs. class
Object Class
Object is the creation
of a class within a program to be used.

Class is the description/


blueprint of the object.

Source Code is the file where


the class is written.

Compilation translates the source


code into a language the computer
can understand.
Class
◦ Class = blueprint
◦ Contains declarations of the state and
behavior
◦ State: data members, instance variables, fields
◦ Behavior: public methods (interface)

◦ Can create many objects from the same


class.
Object uniqueness
◦ Each object has its own attributes that are
unique to it.
◦ Examples
◦ Student
◦ Turtle
Data member
◦ Stores the state for an object.
◦ Typically declared as private and at the top of
the class.
◦ Data members are initialized in the constructor
for the class.
A constructor
◦ A special method that is used to create
an object (instantiation)
◦ The name of the constructor is the same
as the name of the class.
◦ Must match exactly including case.
◦ Constructors do not specify a return type.
◦ Usually set initial values to the data
members
◦ Example constructor declaration
public ScribbleController() {
// Initialize object
}
Default constructor
◦ Constructor that doesn’t have any
parameters.
◦ Typically used to set data member values to
null or 0.
Object initialization
◦ A constructor is invoked when object of a
class is instantiated.
◦ A constructor is used to initialize/set up an
object.
◦ Typically initializes the data members associated
with the class.

◦ Accessing a data member within a class:


◦ this.dataMemberName
◦ Recommended approach when accessing any
data member.
◦ dataMemberName also legal as long as a local
variable doesn’t have the same name.
Constructing/creating an
object to use
◦ An object must be instantiated/allocated
before it can be used.
◦ Use the new operator
◦ Calls a constructor of the object.

this.turtle1 = new ScribbleTurtle();

◦ A data member that is a class only needs to be


instantiated once. If you reinstantiate, a brand
new object is created and assigned to the
variable/data member.
Using an object
◦ Call the methods the object has in order to do something with the
object: method call

this.turtle1.stepForward();
this.turtle2.lowerTail();
Next class
◦ Methods and refactoring
◦ Review

You might also like