Class Fundamentals BCIS 3680 Enterprise Programming

advertisement
Class Fundamentals
BCIS 3680 Enterprise Programming
Overview
Building Your Own Classes


Members of a class



Storing and accessing values in an object


2
Variables (instance and static)
Methods (instance and static)
Constructor methods
Getter and setter methods
Class
A class defines a number of properties (variables) and
actions/behaviors (methods).


An object created from this class will have those variables and
methods.

Variables are used to store data.

Methods are used to specify action.
3
Object vs. Class
Object reference



Identifier (name) of the object
Holds the address of the object

A class is a template for making objects.

An object is an instance of a class.

The process of creating an object out of a template (class) is
called instantiation, “creating an instance of the class”, etc.

Remember the naming convention:


4
The name of a class starts with an uppercase letter.
The name of a variable starts with a lowercase letter.
Creating Objects
Two things required to create an object:


Declaring an object reference for the new object,
ClassName objRef; e.g., Student cobStudent;

Using the new keyword to actually create the object,
objRef = new ClassName([arguments]); e.g.,
cobStudent = new Student("ITDS", "Undergrad");
The two steps may be combined into one:

ClassName objRef = new ClassName([arguments]);
Student cobaStudent = new Student("ITDS",
"Undergrad"); // One step
5
Using Objects
To use an object’s variables and methods, you use the “.”
operator (dot notation).

objectName.variableName
cobStudent.dept = "Marketing";
objectName.methodName([arguments]);
cobStudent.regClass("BCIS3680");
6
Instance Variable
Instance variables are used to store data specific to a particular
object.
An instance variable doesn’t exist (no memory location is assigned to
it) until an object of that class is created.
All objects of the same class have the same instance variables.
However, for each object, the variables store values that are unique to
that object.
Example:









7
The Student class has an instance variable called untId.
alice and bob are two instances of the Student class.
In the alice object, the untId variable contains the value 10101111.
In the bob object, the untId variable contains the value 10102222.
Static Variable
A class may also contain static variables.
Once a static variable is defined in the class, it comes into being
immediately. No instantiation is needed.
Static variables can be accessed from outside of the class by
following the ClassName.staticVarName syntax.
Values stored in static variables are not tied to any particular
instances of the class. Rather, they are relevant at the class level.
Example:








8
The Student class has a studentCount static variable.
The number of all Student objects ever created can be stored in the
studentCount variable.
It is not related to any particular Student object. If it were, we could have
a “the-chicken-or-the-egg” problem.
Instance Method
Instance methods are used to define actions that an object of the class is
capable of performing.
An instance method cannot be called until an object of that class is created.
An instance method is defined the same way for objects of the same class.
However, even if the action is the same, in each object, the action works on
data unique to that object (stored in the respective instance variables).
Example:








9
The Student class has an instance method called showStudentId().
alice and bob are two instances of the Student class.
When called on the alice object, the showStudentId()method displays
the value 10101111.
When called on the bob object, the showStudentId()method displays
the value 10102222.
Static Method





A class may also contain static methods.
Once a static method is defined in the class, it comes into being
immediately. No instantiation is needed.
Static methods can be accessed from outside of the class by
following the ClassName.staticMethod() syntax.
It can be used to perform action that is relevant to all instances of the
class.
Example:



10
The Student class has an addToCount()static method and a
getStudentCount()static method.
The addToCount()method increments the student count whenever a
new student object is instantiated.
The getStudentCount()method displays the current count of student
objects.
Members of A Class
11
The OOP “PIE”
12
Encapsulation

A fundamental concept in OOP.

The values of instance variables inside a class shouldn’t be
changed arbitrarily by other classes.


They should be declared as “private”.
Manipulation of their values are done only by special-purpose
methods inside the class.



13
These methods are public and “exposed”.
Setting values is possible only through calling these methods.
If program logic requires that these values to be changed, regardless
of where the program execution is done, these special-purpose
methods must be called.
Encapsulation


For example, suppose the main method is inside the Driver
class and it needs to set the value of studentID of a
Student object called alice,

It shouldn’t do: alice.studentID = "12345";

Instead, the setter method of that property should be run:
alice.setStudentID("12345");
Whether a field or method is accessible (visible) to other classes
is controlled by access modifiers.


14
public (UML sign + ) – All other classes can access the member.
private (UML sign - ) – Other classes must access the member
through special methods defined in this class.
UML Representation of a Class
15
+ public - private
Access Modifiers
Visibility
Public
Protected
<None>
Private
Within the same class
Yes
Yes
Yes
Yes
From any class in the same
package
Yes
Yes
Yes
No
From a subclass in the same
package
Yes
Yes
Yes
No
From a subclass outside the
package
Yes
Yes*
No
No
From any non-subclass class
outside the package
Yes
No
No
No
16
* Through inheritance
Storing Values to Instance Variables

Constructor Methods



A constructor is a special method that is run when an object is
created. It is typically used to set initial (default) values for instance
variables.
A class may have more than one constructor, i.e., constructors often
are overloaded.
Setter (mutator) Methods



17
A setter method is a void method that performs an action (set the
value of an instance variable).
It takes a parameter – the value to be stored in the variable.
It does not return a value.
Accessing Values of Instance Variables

Getter (Accessor) Methods


18
A setter method is a value-returning method that returns a value (the
value of an instance variable).
It does not have parameters.
Constructor





When an object is instantiated, the instantiation process runs the
class’ constructor method.
If the business rules of your application require other initial
values for (some of all) variables in your class, then you need to
write a constructor and assign initial values to those that need
them.
A constructor may also perform some initial actions in addition to
or instead of setting initial values for variables.
Besides initializing instance variables, a constructor may also
work with static variables/methods of the class.
A constructor must use the same name and capitalization as the
name of the class.
19
Default Initial Values

If you haven’t defined a constructor for the class, Java will create
a default constructor for you
Data Type
byte, short, int, long
20
Default Value
0
float, double
0.0
char
space
boolean
false
Any object reference (e.g., String)
null
Overloaded Constructor

Often, even though objects are instantiated from the same class,
you want their variables to be initialized differently or different
sets of variables to be initialized.

To achieve that, you write a few different constructors
accordingly.

Constructors often are overloaded.
21
Setter Method


The program logic may need to change the value of an instance
variable after it is initialized by the constructor. To do that, the
setter method of that variable needs to be called.
The design pattern of a setter:





22
Access modifier: public
Return value: void
Naming: setVarName
Parameter list: one and only one parameter – (dataType
paramName)
Method body: although more complicated assignment may be needed
sometimes, typically the method contains only one assignment
statement that assigns the parameter value to the variable –
varName = paramName;
Getter Method

A getter method retrieves the value of an instance variable on
behalf of methods in external classes.

The design pattern of a getter:





23
Access modifier: public
Return value: <dataTypeOfVar>
Naming: getVarName
Parameter list: ()
Method body: although more complicated actions may be needed
sometimes, typically the method contains only one statement that
returns the value of the variable – return varName;
Access Method Examples

Example:
// Declare the property
private double unitPrice;
…
// The setter method
public void setUnitPrice (double price) {
unitPrice = price;
}
// The getter method
public double getUnitPrice {
return unitPrice;
}
24
The this Keyword


If inside a constructor or setter method, the parameter name is the
same as the name of the instance variable that will be assigned the
parameter’s value, there should be a way to differentiate the
“namesakes.”
The this keyword is used to refer to the object itself.


Variable name preceded by this and a dot refers to the instance
variable itself.
Variable name standing by itself refers to the parameter.
public void setUnitPrice (double unitPrice)
{
this.unitPrice = unitPrice;
}
25
Download