Objects and Classes
Class Definition
- Programming in Java means writing class definitions (as well as
using and extending existing classes) for the objects in the
application.
- Principles behind good OO Design
- Encapsulation - a class holds all information related to an
object, both the data fields and all the methods.
- Information hiding - the author of a class can make methods and
data visiable/accessible or hidden/inaccessible to methods in other
classes. This helps to insure the integrity of the data within
the class.
- Generalization/Specialization - one class can be inherited by
another class. This allows for the reuse of all class methods/fields.
The
new class adds more fields and methods specific to its needs. Chapter
10
has more on this.
- A class definition consists of variables (what data is
stored, the "state" of the object) and methods (how the data is
processed, the "behavior" of the object).
- A class definition serves as a template for the creation, or
instantiation, of individual objects during the execution of the
program.
- Classes have special constructor methods that are
executed when an instance of the class is created. The constructor
method takes on the same name as the class, has no type (no return
value), and should be public. For example, you may have a class named
Employee, this class could be used to create an Employee object
for all the employees in a company. Each time an Employee is created, a
constructor is run and passed parameters (SSN, Name, job title, etc),
that are used to initialize the employee.
- Examples of objects used in business programming, Employee,
Customer, Order, Product, Transaction, Account. These often mirror
tables in relational databases.
How is a class defined? You must answer the following 5
questions:
- What tasks will the object perform?
- What information will it need to perform its tasks?
- What methods will it use to process its information?
- What information will it make public for other objects?
- What information will it hide from other objects?
Example Rectangle:
- Length and width are private variables therefore they are
encapsulated within the Object and hidden from being able to be
manipulated by other
objects.
- The Rectangle method (constructor) assigns initial values
to length and width.
- The calculateArea, calculateCircumference methods processes the
variables and returns a result (the area, circumference of the
rectangle).
/*
* File: Rectangle.java
*
* Description: This program represents a geometric rectangle.
* This class is not runnable, because it does not have a main() method.
*/
public class Rectangle
{
private double length; // Instance variables, this one is private
double width; // this one is package private
public Rectangle() // Default constructor, one that takes no parameters
{
length = 0;
width = 0;
}
public Rectangle(double l, double w) // Constructor method
{
length = l;
width = w;
} // Rectangle() constructor
public double calculateArea() // Access method
{
return length * width;
} // calculateArea()
public double calculateCircumference()
{
return length*2 + width*2;
}
// accessor method for length
public double getLength()
{
return length;
}
// mutator method for length
public void setLength(double l)
{
length = l;
}
} // Rectangle
Class definitions, some tips
- Define all attributes first, then define the methods
- Define the constructor(s) as the first method (following the
attributes)
- Make sure that once the constructor completes, that the object
is in a valid state, that is all attributes are initialized to valid
values.
- Define one default constructor, one that takes no parameters.
- Do not make an attribute public unless you have a good reason
- Define methods as "public" unless there is a need to restrict
their access
- Create an accessor (get) method and a mutator (set) method for
variables as needed.
- Do not embed constants or literals in your code, instead, define
them as constants using the "final" keyword.
- Class names - mixed case, first letter should be capitalized,
e.g. SalariedEmployees. Must be stored in a file by the same name, e.g.
SalariedEmployees.java
- Methods and Attributes (instance variables) - mixed case, first
letter should be lower case, e.g. hourlyWage
- Always define a toString() method, see the Object class below.
Defining Classes
[modifer] class ClassName [extends SuperClassName]
[implements ImplementedClassName] {
.... define attributes and methods }
- modifers (optional)
- final - implies that this class cannot be inherited,
i.e. it cannot be a superclass for another class
- abstract - implies that this class cannot be
instantiated, i.e. you cannot create an instance of this class using
the "new" operator. This class must be inherited.
- public - this class can be accessed outside its
package (note, only 1 public class per source file)
example:
public class Pet {
String breed;
double weight;
String name;
String ownersName;
// constructor method
public Pet()
{
breed = "unknown";
weight = 0;
name = "unknown";
ownersName = "unknown";
}
public Pet(String b, String n)
{
breed = b;
name = n;
}
public void setWeight(double w)
{
weight = w;
}
public double getWeight()
{
return weight;
}
public String toString()
{
return name +" : " + breed;
}
} // end of the class
Attributes / Variables:
- Definitions
- Variables are places where information can be stored
- Instance variables are another name for class
attributes. these variables are defined within the class statement, but
not within
a method. They can be access by all the methods in the class, and
depending on their access specifiers, by methods of other classes as
well.
Each instance of the class will have a separate value for this
variable,
e.g. for an Employee class, each Employee instance would have an
instance
variable called name that could take on their own values.
- Local variables are variables defined within a method
definition and can only be accessed by statements in that method
- Class variables are variables that are defined within
the class statement, but not within a method. They are denoted with a
"static" storage specifier. They can be access by all the methods
in the class, and depending on their access specifiers, by methods of
other classes as well. An instance of the class does not have to be
made inorder to use them. Each instance of the class will use the same
value for this variable. If one instance of the class changes the value
of the variable, then it is
changed for all instances of the class. E.g. for an Employee class, if
the
attribute payRate were defined with the static storage specifier,
then
each Employee instance would have an instance variable called payRate
that
would take on the same value (you may not want to do this in real life).
- Creating Variables
- You must declare variables that you use before you use them!
- Local variables should be declared at the beginning of the
method
- Instance and class variables should be declared at the
beginning of the class.
- Variable names are case sensitive
- More than one variable can be declared on a line
- double height, weight, width;
- Variables can be declared and initialized on the same line.
- The scope of an identifier determines
where it may be used in the program.
[access specifier] [storage specifier(s)] TYPE attributeName
[ = initial value] ;
- access/visiblity specifiers (optional)
- private - can only be accessed by this class
- protected - can be accessed by methods in this class
as well as by methods in classes that inherit this class
- public - can be accessed directly by methods in other
classes (avoid this at all costs)
- none - in this case the data item can be accessed by methods in
this class and by methods in other classes in the same package
- storage specifiers (optional)
- static - defines the attribute as a Class Variable,
that is, there is only one instance of this variable regardless
of the
number of objects created. Whenever this varible is changed, it changes
for all instances of the class. The variable can be accessed without
creating
an instance of the class.
- final - defines the attribute as a constant, ie a
variable whose value never changes. final requires an
intial value
and may be used in conjunction with static. You should name
final
attributes using all capital letters.
- TYPES
- char - 16 bit unicode character
- byte - 1 byte (-128 to 127)
- short - 2 bytes (-32768 to 32767)
- int - 4 bytes (-2,147,483,648 to 2,147,483,647)
- long - 8 bytes (-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)
- float - 4 bytes (7 digits of precision +- 1.40E-45 to
+- 3.40E+38)
- double - 8 bytes (15 digits of precision +- 4.94E-324
to +- 1.79E+308
- boolean - may hold the value true or false
- String - defines as a standard string object that can
be assigned variable length strings, e.g "Barney Fife" (note the "S" in
string is capitalized since it is an object, not a primative type).
Defining Methods
[access specifier] [storage specifier(s)] TYPE methodName(arguments)
{ local variables and statements }
- access/visibility specifiers (optional)
- private - can only be accessed by this class
- protected - can be accessed by methods in this class
as well as by methods in classes that inherit this class
- public - can be accessed directly by methods in other
classes
- none - in this case the data item can be accessed by methods in
this class and by methods in other classes in the same package
- storage specifiers (optional)
- static - defines the method as a Class Method, that
is, a method that can be called without first creating an instance of
the object. Class Methods can only access Class Variables (static) and
their own local variables.
- final - defines the method as one that cannot be
overridden, that is classes that inherit a class with final methods
cannot redefine
those methods
- abstract - defines the method as abstract, that is, a
method with no body. Abstract methods can only be placed in abstract
classes. They are used to define the interface to a method, the actual
implementation is up to the class that inherits the abstract class.
- TYPES
- May be any type, object, or an array. See types listed for
attributes. If the return type is not void, then the method must
specify a value of the appropriate type on the return statement.
- constructor methods do not have a type
- void - special type that indicates that this method
does not return a value.
- arguments (optional)
- Lists variables and types that are passed to the method.
- the variable type is specified before each name
- commas separate the items in the list.
- Example:
public static float solvePythagorium(float a, float b)
{
float c;
c = Math.sqrt(Math.pow(a,2) + Math.pow(b,2));
return c;
}
Constructors
- constructors are run when an instance of the class is created
(new operator)
- methods with the same name as the class (including the first
capital letter)
- no return type
- usually declared as public
- you may have more than one constructor method, but each must have
a unique parameter list
Naming conventions:
- Class names - mixed case, first letter should be capitalized,
e.g. SalariedEmployees
- Constructor methods have no type and have the same name as the
class.
- Methods and Attributes (instance variables) - mixed case, first
letter should be lower case, e.g. hourlyWage
- Local variables - all lower case
- Constants - all capitals
- The first character of each name must be a letter, the other
characters may be letters, numbers, and the under_score character.
fNames cannot be the same as JAVA keywords (e.g. new, if, class,
public).
- accessor methods, ones that just return a class variable should
start with the word "get", e.g. getWage, getHeight
- mutator methods, ones that change a class variable should start
with the word "set", e.g. setHeight, setWage.
Creating and using Classes and Objects
- in order to create an object and use its methods you must first
instantiate it (i.e. create an instance of the class). This is done
with the new operator.
- e.g.
Rectangle r1 = new Rectangle(10,20); // create a
rectangle with a length of 10 and a width of 20
Rectangle r2 = new Rectangle(); // create a with a length and width of 0
- the new operator allocates space for the object and calls the
appropriate constructor method, passing the data you provide. In the
case of r1, 10
is passed for the length and 20 for the width. The new operator returns
a "reference" or address of the object. This should be saved in a
variable
whose type is the objects class, in this case variable r1 is of type
Rectangle.
- now r1 can be uses to perform calculations for that particular
rectangle, use the "dot" notation, e.g. r1.calculateArea()
- e.g.
System.out.println("The area of r1 is
"+r1.calculateArea());
System.out.println("The circumference of r1 is
"+r1.calculateCircumference());
- r2 is created and can be used similarly, however, r2 is created
using the default constructor. Java determines which constructor to use
by matching the data in the new statement with
the possible constructors, chosing the one that matches.
- an object can refer to itself using the "this" keyword.
- Rectangle had two data items, one was private, one
package-private (default).
- For a method in another class to
access a private variable, then the accessor method (if present must be
called). e.g.
- double l = r1.getLength();
- r1.setLength(2.3);
- For a method in another class within the same package to access a
package private variable, then all it has to do is to use the dot
notation
- double w = r1.width;
- r1.width = 42;
Object Class
- All classes automatically inherit the Object
class.
- This provides each class with some built in capability.
- You should redefine the toString method and the equals method of
the Object class to give your class custom capability.
- toString method returns a string representing the object and
this string is displayed in combo boxes and list boxes that the object
is placed into.
- equals() allows your object to determine if it is the same as
another object.
class Employee {
String
name;
// instance variable, every employee will have their own name
double payRate; //
instance variable
...
public void raisePay() {
double percent = .03;
// define a local variable holding the percent raise
payRate = payRate *
(1+percent); // increase pay
}
public String toString()
{
return name; // return the employee's
name for possible display
}
public boolean equals(Object other)
{
String text = toString();
return text.equals(other.toString());
}
}