Objects and Classes 3: Happy New Year
Objects and Classes 3: Happy New Year
and
Classes
3
Happy
New
Year
J
CMSC22 OOP
Objec:ves
Review
of
Objects
and
Classes
Class
Members
Instance
variables/methods
Class
variables/methods
Review:
Classes
Classes
dene
the
proper:es
and
behaviors
(methods)
objects
that
belong
to
it
have.
A
Class
is
a
structure
composed
of
ANributes
(instance
and
class
variables
Methods/Opera:on
that
manipulate
the
data
(instance
and
class
methods)
public class Car{ String color; String platenumber; int speed; //constructor with parameters for ini2aliza2on public Car(String nplatenumber, String ncolor){ platenumber = nplatenumber; color = ncolor; } public void stop() { speed = 0; } }
public class CarExample{ public sta:c void main(String args[]){ //pass the parameters to the constructor Car car1 = new Car(XYZ123,RED); Car car2 = new Car(ABC456,GREEN); } }
Car.
java
Car
String
platenumber;
String
color;
int
speed;
stop()
accelerate(int)
repaint(String)
Program
Addi:onal
Terms:
Instance
aNribute
/variable
ANribute
specic
to
an
instance/object.
Each
object
of
the
class
have
the
same
set
of
proper:es
BUT
may
have
dierent
values
for
each
property.
Instance
method/opera:on
Method
where
the
result
of
which
is
dependent
on
the
current
state
of
the
object
in
ques:on.
Car.
java
Car
String
platenumber;
String
color;
int
speed;
Program
stop()
Addi:onal
Terms
Class
aNribute/variable
ANribute
that
is
common
to/reected
in
all
objects
in
the
class.
I.e.
Global
(but
not
exactly).
Class
method/opera:on
Method
that
is
common
to
all
objects
of
the
class
and
that
the
result
of
which
is
NOT
:ed
to
any
par:cular
instance
of
the
class.
Car.
java
Car
String
platenumber;
String
color;
int
speed;
Int
numberOfCars;
stop()
getNumberOfCars()
Program
Also
Instance
methods
can
access
instance
variables
and
instance
methods
directly.
Instance
methods
can
access
class
variables
and
class
methods
directly.
Class
methods
can
access
class
variables
and
class
methods
directly.
Class
methods
cannot
access
instance
variables
or
instance
methods
directly
Note
on
Destructors
Destructors
Specialized
methods
that
deallocate
memory.
May
be
implicitly
or
explicitly
called
(i.e.
in
C++)
Java
doesnt
have
destructors
because
of
its
auto
garbage
collec:on
features.
Note
Reusability
Usefulness
of
the
class/objects
in
more
than
one
object.
Types
of
Classes
En2tyClasses
/
DataClasses
Classes
whose
objects
encapsulate
the
data
used
in
a
system
Data-related
objects.
E.g.
String,
Student,
Car
Types
of
Classes
U2lityClasses
Classes
that
maintain
u:lity
methods
and
usually
are
not
instan:atable
java.lang.Math
Types
of
Classes
Singleton
Objects
{Class}
Object
when
instan:ated,
no
other
object
of
the
same
class
exists
in
the
given
context.
E.g.
java.lang.System
Types
of
Classes
ControlClasses,View(Interface)Classes
Control
Classes
for
Logic
View
Classes
for
the
User
Interface
Create
a
Class
Four
instance
variables
Two
class
variables
Three
instance
methods
One
class
method