Computer Science I Classes and Objects Professor: Evan Korth New York University Evan Korth New York University.

Download Report

Transcript Computer Science I Classes and Objects Professor: Evan Korth New York University Evan Korth New York University.

Computer Science I
Classes and Objects
Professor: Evan Korth
New York University
Evan Korth
New York University
Road Map
•
•
•
•
•
•
Introduction to object oriented programming.
Classes
Encapsulation
Members
Objects
Constructors
Evan Korth
New York University
Object Oriented Programming
• Emphasis is placed on nouns or objects.
• Nouns (objects) have properties and
behaviors.
• How do we build these objects?
• How do we represent their properties?
• How do we define their behaviors?
Evan Korth
New York University
Classes
• The main building blocks of Java programs.
• Defines objects of the same type. Like a
blueprint.
Evan Korth
New York University
Classes (cont)
• Every .java file has one or more classes. Only one
of the classes can be a public class.
– That class must have the same name as the .java file.
• If the class has an method called main(), execution
can begin in that class. (Therefore, you can test a
class by adding a main method to it.)
• If there are other classes in the file, they cannot be
public classes.
Evan Korth
New York University
Encapsulation
• Encapsulation refers to the process of
combining elements to create a new entity.
• You encapsulate the properties (attributes)
and behaviors (activities) of an entity into a
class.
• Encapsulation also enables us to hide the
implementation of a class to other classes
(information hiding / abstraction).
Evan Korth
New York University
Designing Classes
• A class declaration includes members of the
class.
• A member can be either a data member or a
method member.
• A data member (AKA field) is used to
define state (attributes or properties) of the
entity.
• A method member is used to define the
behaviors of the entity.
Evan Korth
New York University
Data members
• Data members can be a primitive type or a
reference to another object*.
– Primitive types are integer types, floating point
types, characters and booleans. (Note: an int is
not the same as an object of type Integer)
• The scope of a data member is the entire
class, no matter where within the class it is
declared.
* More on object references in a moment
Evan Korth
New York University
Default values for data members
• 0 for all numeric type variables (including
both floating point types and all integer
types)
• \u0000 for char variables
• null for reference variables*
• false for boolean type variables
• Note: No default values for local variables
(variables declared inside a method).
* More on object references in a moment
Evan Korth
New York University
Objects
• An object is an instance of a class.
• If we think of a class as a blueprint, an
object is one model created from that
blueprint.
• You can create any number of objects from
one class.
• An object is distinctly identified by an
object reference (except for anonymous
objects).
Evan Korth
New York University
Declaring object references
• In order to reference an object, we need an
object reference variable.
• To declare an object reference variable we
use the syntax:
ClassName objectReferenceName;
• The above statement creates a variable
objectReferenceName which can
reference a ClassName object. It does
NOT create an object.
Evan Korth
New York University
Instantiating objects
• In order to create an object, we use the new
keyword along with a constructor* for the class of
the object we wish to create.
• To refer to the object, we “point” an object
reference variable to the new object.
objectReferenceName = new Constructor();
• The declaration and instantiation can be combined
as follows:
ClassName objectReferenceName = new ClassName();
– Note: the name of a constructor is the same as the name of the class
* More on constructors soon
Evan Korth
New York University
Accessing Members of a Class
• Within a class you can access a member of the
class the same way you would any other variable
or method.
• Outside the class, a class member is accessed by
using the syntax:
– Referencing variables:
objectReferenceName.varName
– Calling methods (sending messages):
objectReferenceName.methodName(params)
Evan Korth
New York University
Constructors
• Constructors are special methods that
instantiate objects.
• A constructor is invoked with the new
operator.
• A constructor should initialize the class
variables. If the variables are not
initialized, default values are used.
• A constructor does not have a return type.
• A constructor’s identifier (name) is the
same as the class itEvan
constructs.
Korth
New York University
Constructors continued
• Constructors can be overloaded but each one must
have its own signature.
• A constructor with fewer arguments can call a
constructor with more arguments (we will see how
to do this soon).
• If no constructor is defined, a default constructor
is automatically supplied which accepts no
parameters. Variables are initialized to their
default values.
• If one constructor is explicitly defined, the
automatic default constructor is no longer
available. In such case, if you want a no
parameter constructor, you must define it yourself.
Evan Korth
New York University
Road Map
• Dealing with multiple files
• modifiers
• Static variables
Evan Korth
New York University
review
• What is meant by the term encapsulation?
• What are the default values for data
members?
• What does it mean to instantiate an object?
• What does this statement do?
Integer i;
Evan Korth
New York University
Review
• Given:
Integer i;
What does the following statement do?
i = new Integer(100);
• Generally, what should a constructor do?
• What is a default constructor?
Evan Korth
New York University
Modifiers
• Java provides us with several keywords used to
modify the accessibility of variables, methods and
classes.
– Visibility modifiers
• public
• private
• protected
• (None)
– others
• static
• final
• abstract
Evan Korth
New York University
Principle of least privilege
• You should pick the modifier that allows
the least privilege for other classes while
allowing your code to do what it needs to
do.
• This helps reduce debugging time by
localizing potential problem areas.
Evan Korth
New York University
Data member modifiers
• No modifier (default) means the data is visible in the
package in which it is declared.
• public means the data is visible to everything.
• private means the data is visible only within the
class in which it is defined.
– Trying to access private data from another class will result in
a compile time error.
• final means the variable cannot be changed.
• There are two other modifiers applicable to variables:
– static : We will discuss in a moment
– protected: We will discuss later in the semester.
Evan Korth
New York University
Accessor methods
• When a data member is declared to be
private, we still need a way to refer to that
data. A method used to change or retrieve a
private data item is referred to as an
accessor method.
• Two kinds of accessor methods are the get
method and the set method.
Evan Korth
New York University
Get methods
• A method that is used to retrieve the value
of a data object is referred to as a get
method.
• Also known as a getter.
• Get method header should look like this:
public returnType getPropertyName ()
• It may just return a data field or it may
calculate the value. Remember information
hiding.
Evan Korth
New York University
Predicate methods
• A get method that returns a Boolean value
should have a header like this:
public boolean isProperty ()
• It can simply return a Boolean data field or
it can use a Boolean formula to calculate
it’s data. Remember, information hiding!
Evan Korth
New York University
Set methods
• Methods used to set or change the value of a
data method are referred to as set methods.
• Also known as setters and mutators.
• Header of set method will look like this:
public void setProp (propType var)
Evan Korth
New York University
Data modifiers (cont)
• A data member can be either an instance
variable or a static variable (also known as a
class variable).
Evan Korth
New York University
Static variable (AKA class variable)
• A static variable has only one value no matter how
many objects are instantiated from a class. The value is
shared by all instances of the class.
• A static variable does not need an instance of the
class in order to be accessed.
• You can access a static variable either with
ClassName.varName (better style), or
objectReference.varName notation.
• For static variables, every object of the class refers to the
same memory location.
• Static variables can be accessed by static methods OR
instance methods.
• The memory for a static Evan
variable
is allocated when the
Korth
New York University
class is loaded into memory.
Instance variables
• An instance variable has a unique value for each
object of that class.
– This does not mean that two objects cannot have the
same value; it does mean that those values will be
stored separately in memory.
• You can access an instance variable only with
objectReference.varName notation.
• No memory is allocated until an object is
instantiated.
• Can be accessed by instance methods only (not
static methods -- we will talk about static methods
in just a moment). (i.e. not by static methods)
Evan Korth
New York University
Scope of data members
• Whether a data member is a class variable
or an instance variable, it’s scope is the
entire class. It does not matter where in the
class, the variable is declared.
• Remember, if they are not initialized, data
members are assigned a default value.
Evan Korth
New York University
Local method variables
• Do not automatically get initialized.
– Using them without initializing them is a
compilation error.
• Cannot have visibility modifiers.
• The scope of a local method variable starts
where it is declared. It ends at the end of
the block where it was declared.
Evan Korth
New York University
Method members
• Methods are used to define the behaviors of
an object.
• They can be overloaded.
– Having more than one method in a class with
the same name is referred to as method
overloading.
– Each of the methods must have a different
method signature. That is, they must have
different argument lists.
Evan Korth
New York University
Method modifiers
• No modifier means the method is visible in the package
in which it is declared.
• public means the method is visible to everything.
• private means the method is visible only within the
class in which it is defined.
– Trying to call a private method from another class will result
in a compile time error.
• static means it is a static method. Static methods can
use other modifiers as well.
• There are three others (final, protected and
abstract) which we will discuss later in the semester.
• There are still others which we will not discuss this
Evan Korth
semester.
New York University
Static methods (AKA class methods)
• Can be called without an instance of the
method.
• All the methods in the Math class are static
methods which is why we can call them
without a Math object. In fact, we cannot
instantiate an object of the Math class.
• You can call a static method either with
ClassName.method (args) (better style),
or objectReference.method (args)
notation.
Evan Korth
New York University
Instance methods
• Can only be called after an object is
instantiated.
• You can call an instance method only with the
objectReference.method (args)
notation.
• An instance method acts on the specific
instance for which it has been called.
Evan Korth
New York University
Road Map
• Class modifiers
• Garbage collection
• Naming conflicts
– this
• Reference members
Evan Korth
New York University
review
•
•
•
•
What does encapsulation mean?
What is a data member?
What is a method member?
What is the difference between an object and a
class?
• What does the following line of code do?
– Integer i;
• What is i above?
• What happens if you make a class without a
constructor?
Evan Korth
New York University
Review (cont)
• What do the following modifiers mean
when applied to a data member?
– final
– static
– public
– private
• What if there is no modifier?
• What is the principle of least privilege?
Evan Korth
New York University
Review (cont)
• What data type does a set method usually return?
• What parameter does a get method usually take?
• A class has 3 objects instantiated, it also has a
static variable called x and an instance variable
called y.
– How many x values are stored in memory?
– How many y values are stored in memory?
• What is the scope of an instance variable?
• Can you call an instance method without an
instance of the class?
Evan Korth
New York University
Class modifiers
• No modifier (default) means the class is
visible in the package in which it is
declared.
• public means it is visible to everything.
• There are two others (final and
abstract) which we will discuss later in
the semester.
Evan Korth
New York University
Garbage collection
• When an object is no longer referenced by any
reference variable, that object is referred to as garbage.
• Java automatically tracks garbage objects and frees its
memory when the garbage collector runs.
• We do not have direct control over when the garbage is
collected.
• We can suggest to the compiler to collect garbage but it
is not guaranteed that it will run.
• To suggest garbage collection we make the following
method call:
– System.gc();
Evan Korth
New York University
Anonymous objects
• An object without a reference is called an
anonymous object.
• It is created, used and immediately marked
as garbage.
Evan Korth
New York University
Variable name conflicts
• It is possible to have a variable name in a
method with the same name as a data
member in a class.
• In such case, the local method variable
“hides” the data member variable.
Evan Korth
New York University
Keyword this
• The keyword this is used within a class to refer
to the specific instance of the class that is being
used.
• A variable in a class’ method that has the same
name as a field will “shadow” the field. You can
access the field using the this keyword.
• You cannot use the this keyword in static
methods. (why?)
Evan Korth
New York University
Another use for this
• this (args) in a constructor will invoke
another constructor of that class.
– If you call another constructor from a constructor, it
must be the first line in the calling constructor.
• This is useful when you overload your
constructors. In general, a constructor with fewer
parameters should call a constructor with more
parameters.
Evan Korth
New York University
Composition
• The term composition refers to the practice
of having an object as a data member within
another object.
• What is actually stored is a reference to the
member object. (therefore we can have self
referential objects)
• The default value for a reference variable is
null.
Evan Korth
New York University
Passing reference variables to
methods
• All variables in Java are passed using call by
value. However, since object variables are really
references to objects, passing an object is
simulated pass by reference.
– Objects passed to a method and modified by that
method will have the changes reflected in the calling
method.
– Primitive variables passed to a method and modified by
that method will NOT have the changes reflected in the
calling method.
Evan Korth
New York University