Title: Objects Classes and Inheritance
1Objects Classes and Inheritance
2Vocabulary (1)
- A class is a template or blueprint from which
objects are created - All Java code exists inside a class NO
EXCEPTIONS - We don't have Module types and other types like
VB .NET - Encapsulation combines data and behavior into a
single package - Encapsulation supplies black box behavior
- Object is the Java superclass and is analogous to
the .NET System.Object class - Classes extend other classes through inheritance
3Vocabulary (2)
- The data in an object are called instance fields
- Static (shared) fields are shared among multiple
class instances - No matter the number of instances of a class
there exists one and only one copy of a static
fields - Functions that act on data and change state are
called methods
4What's an Object
- An object has three key characteristics
- Behavior The methods of an object. What the
object can do - State When happens when a method gets called
- The current condition of the object
- Identity How to distinguish an object from
others having the same behavior and state - Each class instance (object) has a unique identity
5Designing a Class
- Designing a class or classes that comprise an
application can be somewhat subjective - Guidelines
- Look at the nouns to describe a system
- These nouns are likely candidates for classes
- Minimize dependencies between classes
- Look at what a class does (verbs)
- These become the methods of the class
- The data in a class also appear as nouns
6Class Relationships
- There are three common relationships between
classes - Dependence (uses-a)
- One class is dependant upon or uses another class
- Aggregation (has-a)
- An order has items
- An employee has payroll records
- Inheritance (is-a)
- A relationship between a more general and a more
specialized class (more in Chapter 5)
7Constructing Objects
- Conceptually .NET and Java constructors are the
same thing - In Java, the name of a class' constructor is the
same as the name of the class (rather than a Sub
procedure named New in VB 6) - The case sensitivity rule still applies
- The new keyword calls the constructor
- Date dateToday new Date()
8Object References
- Classes are reference types
- This is the same as reference types in .NET
- Without the new keyword, a class instance is not
created - We just get a null pointer
- Look at the figures on page 97
- Multiple variables can reference the same object
instance - Again, remember that classes are reference types
9A Word about Depreciation
- Java has various depreciated methods
- Depreciated methods will work but replacement
methods should be used instead - The compiler will flag depreciated methods with
compiler warnings - Avoid the use of depreciated methods because they
may not work with future Java versions
10Some Fun with Dates
- There are two problems in representing dates
- One is keeping track of time and representing a
point in time using either - Astronomical observations
- Atomic clocks
- They add a leap second every year to two at the
end of the day on 12/31 or 6/30. - This is the purpose of the Date class
- The other is attaching a name to a point in time
- This is the purpose of the GregorianCalendar class
11The Date Class
- Time is granular to the millisecond
- Boolean before method tests whether a date is
before the specified date - Boolean after method tests whether a date is
after the specified date - compareTo compares two dates for ordering
- Most of the methods of the Date class are
depreciated and replaced by the methods of the
GregorianCalendar class
12The GregorianCalendar Class (1)
- GregorianCalendar belongs to java.util and is
derived from java.util.Calendar - It is the calendar used by most of the world's
population - There are other religious calendars however
- Without arguments, the constructor uses the
current date and time - With arguments a specific time can be used
13The GregorianCalendar Class (2)
- isLeapYear returns true if the given year is a
leap year - add adds one or more units to a date value
- First argument contains the units
- Second argument contains the number of units to
add
14The GregorianCalendar Class (Example 1)
- Create a GregorianCalendar an initialize it to
the current date - We could have initialized the date using the
constructor - Calendar calendar new GregorianCalendar()
- Date datCurrent new Date()
- calendar.setTime(datCurrent)
15The GregorianCalendar Class (Example 2)
- Get some information about the date
- System.out.println("ERA " calendar.get(Calendar
.ERA)) - System.out.println("YEAR " calendar.get(Calenda
r.YEAR)) - System.out.println("MONTH " calendar.get(Calend
ar.MONTH))
16Java Classes (Introduction)
- In Java, everything is a class
- There is not Module type as in .NET
- A single source file can contain one or more
classes - Only one class can be public in the source file
however - Classes can have one or more overloaded
constructors - Unlike VB .NET, the name of the constructor is
the same as the name of the class - Classes can have one or more methods
17Constructors (1)
- Like .NET, Java classes have a constructor
- The name of the constructor must be the same as
the class name - Similar to C in this regard
- Constructors can be overloaded
- We discuss overloading in Chapter 5
- A default constructor accepts no arguments
- It is possible for one constructor to call
another constructor - Use the this keyword with a different argument
list - Constructors can accept 0 or more arguments
- A constructor without arguments is considered the
default constructor - It is implicitly supplied
18Constructors (2)
- A constructor cannot return a value
- A constructor is never called directly
- It is always called with the new operator
- A default constructor is the one with no arguments
19Constructor Example
- Note constructor name is the same as the class
name - The constructor is storing argument values in
hidden fields - class Customer
-
- public Customer(String cName, String
- cAddress, double cLimit)
-
- customerName cName
- customerAddress cAddress
- creditLimit cLimit
-
-
20Accessors and Mutators
- Java does not support Property Procedures in the
same way as VB .NET - We could just use fields but that would violate
the encapsulation rules - Accessor methods read the value of hidden data
- Prefix the accessor name with "get" to comply
with standard naming conventions - Mutator methods write the value of hidden data
- Prefix the mutator name "set"
21Accessor Example
- Accessor getName returns the value of the hidden
variable "name" - We could use a field but that violates the
encapsulation rules - public String getName()
-
- return name
-
22Mutator Example
- Store the argument value in a hidden field
-
- public void setName(String n)
-
- name n
-
23Working with Multiple Source Files
- A Java program may appear in one source file or
multiple source files - When compiling the main source file, the compiler
recognizes dependencies and compiles all of the
necessary subordinate files - Timestamps are used to determine whether or not
files are out of date - In essence, Java has the UNIX make utility
built inside of it
24Methods
- Methods are nothing more than public procedures
appearing in a class - Private procedures are part of the implementation
rather than being part of the interface - public void raiseSalary(double
- byPercent)
-
- double raise salary
- byPercent / 100
- salary raise
-
25What is this?
- The this keyword references the current instance
of a class - Its equivalent to the VB .NET Me keyword
- public void raiseSalary(double
- byPercent)
-
- double raise this.salary
- byPercent / 100
- this.salary raise
-
26Working with Mutable Objects
- To adhere to encapsulation rules, never return a
Mutable (changeable) object - Side effects occur because of the way object
references work - Instead, return a clone of the object by calling
the clone method - public Date getHireDay()
-
- return (Date)hireDay.clone()
-
27Method Scope
- private methods are hidden inside of a class
- A private method can only be called from the same
class containing the declaration - public methods are exposed to developers
- Public methods can be called from any class
28Final Instance Fields
- Final instance fields can only be set once
- Final instance fields must be initialized in the
constructor - Use final instance fields with read-only
properties - Trying to store a value in a final instance field
will generate an error - Just add the final keyword to the variable
declaration
29Static Fields
- For a static field, only one copy of the data
exists no matter the number of class instances - Similar to the Shared keyword in VB. NET
- Declare a variable with the static keyword
- The static variable exists and can be referenced
even if there is no instance of the class
30Static Methods
- Static methods do not operate on objects
- Static methods are declared with the static
keyword in the same way as static variables are
declared - Static methods CANNOT operate with instance data
- This is logical. Think about why
- Instance methods can operate with static data
- The methods of the Math class are static, for
example
31Primitive Parameters
- As in most languages, parameters are passed by
value or by reference - Unlike .NET, primitive type parameters are ALWAYS
passed by value - The method cannot modify the value of a parameter
and have the modified value returned to the
caller - See figure 4-6 on page 119
32Object Parameters
- When passing an object reference as a parameter,
the called method can modify the object - A copy of the object reference is passed as an
argument so we are referencing the same memory
address from the caller and the callee - NOTE THAT WE ARE NOT CALLING BY REFERENCE SEE
PAGE 121
33Object Destruction
- When utilizing a resource such as a file handle,
the handle should be released before the object
is destroyed - Use the finalize method for this
- finalize is roughly equivalent to a destructor
- finalize gets called before the GC destroys the
object
34Packages
- Multiple classes are grouped into packages
- By convention, use a companys Internet domain
name written in reverse - Packages exist primarily to guarantee the
uniqueness of class names - Packages are roughly equivalent to .NET
namespaces - Packages are organized hierarchically just as
.NET namespaces are organized hierarchically - Standard Java packages appear in java and javax
35Importing Packages
- It is possible to import all the classes in a
package with wildcards - import java.util.
- It is also possible to import a single class
- import java.util.Date
- Package ambiguity can pose a problem
36Package Implementation
- Without a package declaration, all packages are
part of the default package - When creating a package, create files in a
directory structure that matches the package
structure
37Creating Comments with javadoc
- Javadoc is a neat tool used to document classes
by embedding comments directly into the class
module - These comments are parsed by javadoc and used to
build a help system - This is how the Java help system is built
- Simply create a comment with / instead of /
- The comment may contain HTML directives
38Class Comments
- Must appear AFTER any import statements and
before the class declaration - import java.util.
- /
- The ltstronggtEmployeelt/stronggt class
- represents an employee in the organization.
- /
- public class Employee
39Method Comments
- Method comments are created via parameters
- Describe a method parameter
- The tag must precede the method described by the
parameter - _at_param variable description
- Describe a return value
- _at_return variable description
40General Comments
- The program author
- _at_author name
- The program version
- _at_version text
- When the method was introduced
- _at_since text
- Use for depreciated methods
- _at_depreciated text
- A link to another URI
- _at_see uri
41Introduction to Java Inheritance
- Inheritance utilizes an is-a relationship
- Java, like .NET supports single inheritance
- C supports multiple inheritance
- A derived class is created from a base class
- Derived class is often referred to as a subclass
or child class - Base class is often called a parent class or
superclass - Use the extends keyword to create a derived class
from a base class
42A First Inheritance Example
- The Manager class inherits the Employee class
- public class Manager extends Employee
-
43Designing for Inheritance
- Place general methods in the base class
- These methods are automatically inherited in a
derived class - Create methods in the derived class to override
base class members or to create new members - Use the super keyword to explicitly call a base
class method - super is equivalent to MyBase in VB .NET
44A Word about super and this
- super is not a reference to an object
- It is not possible to store into an object
variable the value of super or this - super when called in a constructor calls the base
class constructor - Super must appear as the first statement in the
contstructor
45Preventing Inheritance
- Classes that cannot be inherited are called
sealed classes - Use the final keyword in the class declaration
- Sealed classes are more efficient because dynamic
binding is used instead of static binding - Security is improved
46Polymorphic Behavior and Inheritance
- Object variables are polymorphic
- A variable can refer to a type or a subclass of
that type - Through dynamic binding, the JVM figures out the
correct type
47Casting Object Variables
- The syntax is no different that casting a
primitive type - Casts are commonly used with generic containers
such as an ArrayList - Use to convert a generic object type to an
explicit type
48Abstract Classes
- An abstract class is one for which it is not
legal to create an instance (so much for the
grammar) - Use the abstract keyword in the class declaration
- Abstract class Person
-
49Abstract Classes (2)
- Abstract classes may have both abstract and
concrete members
50Protected Access
- In a nutshell protected is somewhere between
public and private - Protected members are visible to the current
packages and any subclasses derived from classes
in the current package - The access modifier has the same meaning as
protected in .net