Inheritance
- Immutable
objects - immutable objects are ones that do not allow their
contents to be changed after the object is created.
- The String class is an example.
- All fields are declared as private
- No mutator methods provided
- No accessor methods return a reference to the data field.
(e.g. an arrary)
- Scope of
variables
- Variable types
- Class variables - scope is
the entire class
- instance variables are declared without the "static"
modifier, scope is the entire class, memory allocated for each object
created
- static variables are declared with the "static" modifier,
scope is the entire class, all objects share the same memory allocation
- Local variables - scope is
the method
- parameters - defined in
the method header, receive their initial values from the caller of the
method
- variables - defined in the
method body
- memory for these variables
is allocated when the method is called and goes away when the method
exits.
- names for local variables
must be unique within the method.
- local variables with
the same name as class variables "hide" the class variable (unless the
this. modifier is used)
- Class
Abstraction - Creator of the class separates the implementation
of the class from the use of the class.
- Class
Encapsulation - Details of the class design and operation are
kept from users of the class (programmers who use the class).
- Class
Contract - Public methods and constants.
- Generalization
- creation of general purpose class that can be later inherited to
create specific class types, e.g. JFrame
- Specialization - process of creating
a new class that inherits a general class, e.g. a class named
HourlyEmployee might inherit the general class Employee
- Inheritance - is a mechanism that enables one class to
inherit all the behavior and attributes of another class. JAVA only
supports single inheritance, ie a class can have only 1 super class.
JAVA implements inheritance with the extends keyword.
- Super classes and Sub classes - any class that inherits
another class is said to be the sub class. Any class which is inherited
by another class is a super class. Super classes are sometimes referred
to as "base classes" or "parent classes".
- If class A extends class B, then class A inherits all
variables and methods of class B. Therefore you can think of an object
of type class A as having all the varibales and methods defined by
class A as well as
all the variables and methods defined by class B.
- Inheritance is one of the most powerful features of
objected-oriented languages. It enables code reuse by giving a
programming a starting point (super class) to base their work on.
- Interfaces - are collections of methods that a indicate
a class has some behavior in addition to what it inherits from its
superclasses. For example, a class might need to have the ability to
handle both keyboard and mouse inputs, but since JAVA does not allow it
to inherit both classes, then it needs a different mechanism. JAVA
implements interfaces using the implements keyword.
- Uses:
- sometimes you have to use inheritance in order to implement a
feature or a program. For example, applications inherit JFrame, applets
inherit
JApplet, in order to use input verifiers you have to create a class
that
inherits InputVerifier.
- sometimes you see that you are doing the same code over and
over in a program and you want to create a more powerful object
that what the library provides. Example, a SortedListModel class
that takes care of automatically inserting items into a
ListModel in alphabetical order for a JList.
- whenever you can create an object that is a "type-of"
another object.
- For example, assume you have want to create a payroll system
that supports salaried employeees, hourly employees, and part-time
employees. The
system would need to generate paychecks and benefits based on what type
a
particular empoloyee is.
- You could create a payroll system that had Employee objects
that remembers the type in a field (employeeType), then has if or
switch
statements in every method to process based on employee type.
- Alternatively, and better, you could have an Employee
class that holds knowledge common to all employee types, then separate
classes for SalariedEmployee, HourlyEmployee, and PartTimeEmployee. All
of these would
inherit Employee, but add their own information and redefine methods
that
are particular to them.
- The big advantage here is you reduce the number of
"if" statements (always a source for bugs), and allow new types
of employees to be created without having to change code for existing
types (and risking the
introduction of bugs).
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)
Defining Variables
- Rules
- 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.
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;
}
- Overriding Constructors
- to inherit the attributes and methods you use the key word extends,
e.g
class CustomerList extends ArrayList{
CustomerList() {
super(10); // call the Arraylist constuctor
with an initial size of 10
... other constructor statements
}
}
- Thus, the class CustomerList has all the varibables and
methods that ArrayList does.
- In this example the constructor for CustomerList invokes one
the ArrayList contructors using the keyword super
- This must be done as the first statement in the constructor,
if not, then Java will automatically call the default constructor (i.e.
the one with no parameters, super()).
- Overriding methods
- This is done whenever you would like your new class to do
something different with a method than what the super class does.
- For example, if you wanted your CustomerList to have its own
"get" method that uses 1 as the first index rather than 0 you would
define a routine that looks like this:
Object get(int index)
{
// index represents the index based on 1 rather than 0
return super.get(index-1);
// call ArrayList's version of get, adjusting the index
}
- note the use of the super keyword. In order too call the super
class's version of a method, you must use the keyword super before the
method
name. You only need to do this if your override that method.
otherwise,
just use the method name itself.
- in order to override a method, you use the same name and same
parameter list.
- Overloading methods
- You do this when you want to create a method that has the same
name as a method in the super class, but has a different parameter
list. For
example, you decided you want a version of "get" that searches the list
for
a particular customer by name you would create a new version of get
that
would look like this:
Customer get(String gName) {
int i;
Customer c;
for(i = 0; i < size(); i++) {
c = (Customer)get(i);
if(gName.compareTo(c.name) == 0)
return c; //
customer found, just return it (escapes entire method)
}
return null; // name was not found
}
Object class
- Every class is a descendant of the object class.
- If a class is defined without the extends keyword, then its super
class is automatically the Object class
- Object defines a number of methods that are common to all
objects. You can redefine (override) them in order to make your class
behave like
you want it to. The two primary ones you should consider
redefining
are:
- public String toString() - override this to return a printable
version/description of your object.
- public boolean equals(Object obj) - override this to allow
comparison of your object to other objects.
- Example:
public class Employee
{
private String lastName;
private String firstName;
private String socialSecurityNumber;
......
/**
* return employee's name for display in list boxes,
etc
*/
public String toString()
{
return firstName + " "+ lastName;
}
/**
* compare the two employee's sssn numbers to see if
its the same employee (names might not be unique)
*/
public boolean equals(Object obj)
{
return
socialSecurityNumber.equals((Employee)obj.socialSecurityNumber);
}
}
Casting Objects
- Casting can be used to tell the Java compiler to treat an object
of one type like it would another.
- Many of the standard Java library classes (e.g. JComboBox,
ArrayList) store objects of the generic class Object. This allows them
to
store
an object of any classes. However, when you go to retrieve these
objects,
the "get" routines return objects of type Object (the get method used
in
ArrayLists, Vectors, and ListModels is a good example).
Therefore, in order to
reference the method of these objects, it is necessary to cast
them
back to their original definition.
- Example:
Employee e = new
Employee("Doe","Jane","111-22-3333");
comboBox.addItem(e); // adds Jane
Doe's
employee object to the combobox
Employee x = comboBox.getItemAt(0);
// this line
would cause a compile error since get returns a object of type Object
Employee x =
(Employee)comboBox.getItemAt(0); //
this line would be ok.
- rule - it is always possible to convert an instance of a
subclass into a super class. Since Employee is a subclass of
Object, it can be stored like an Object variable.
- rule - when converting a superclass into a subclass, then you
must do explicit casting. Before you do this you should be certain
that
the object you are casting is actually of the correct type, if its not,
then you'll get an exception thrown at you.
- If for some reason you have to write code to process items in a
structure (like a ComboBox or ListModel) that contain objects of
different types (i.e. a ComboBox that contains both Employee and
Customer
objects), then you can
use the instanceof operator to check them before casting and
using
them. Example:
for(int i = 0; i <=
comboBox.getItemCount(); i++)
{
if(comboBox.getItemAt(i)
instanceof
Employee)
{
Employee e =
(Employee)comboBox.getItemAt(i);
....
}
else
if((comboBox.getItemAt(i)
instanceof Customer)
{
Customer c =
(Customer)comboBox.getItemAt(i);
....
}