User-Defined Classes

you are watching: User-Defined Classes here hiddentracks.org


User-Defined
CLASSES in Java

TOPICS

·        
Java Classes

·        
Java User-Defined Classes

o  
Class Definition, Syntax

o  
Class Constructors

o  
Variable Declaration and Object
Instantiation

 

 

OUTLINE

Java Classes

So far, the focus of this class was on procedural decomposition (breaking
complex tasks into smaller subtasks – structured programming using procedural
techniques). Java also provides object-oriented programming (OOP) techniques.
An object-oriented programming language  = a
software system as a set of interacting objects (rather than a set of actions).

OOP Terminology:

  • Class = A collection of a fixed number of components. A
    class defines
    a new data type and describes a group of objects with
    similar properties. The components of a class are called class members,
    and they can be data and methods.
  • Object (or instance) = A programming entity
    that contains state and behavior. In other words, an object is a container
    for a set of data and the operations that need to be performed on it. An
    object is an instance of a class, or a variable of type class. For a class
    named
    SomeClass, “someObj is of type SomeClass“, “someObj is an object of the
    class
    SomeClass“, and “someObj is an instance of the
    class
    SomeClass” mean the same thing.
    Variables of the type class may be created just like variables of built-in
    types.
  • Instantiating a class = creating an
    object.

    When you create an object, you are creating an “instance” of a
    class, therefore “instantiating” a class.
  • State = A set of values (internal data) stored in an object
    (also called domain.)
  • Behavior = A set of actions an
    object can perform (also called operations/methods.)
  • Client (or client program, or client code) = A program that
    interacts with a class or objects of that class (software that declares
    and manipulates objects of a particular class.)
  • Message passing to an object = Invoke a
    member method on a particular object.

You
already know how to use classes and the objects created from them, and how to
invoke their methods because you already interacted with objects from Java
classes you didn’t actually write: String, Scanner, Random, File, PrintStream, etc. Before starting to write your own
classes it helps to remember how you used these pre-existing Java classes. In
such cases, you were acting as a client of these classes and as a client, you
needed to know what methods are available in each class and how to invoke them.
The details of how each method works were not your concern and actually these
details were hidden.

  • Data abstraction: separates the logical
    properties of a data type (what are the possible values, what operations
    will be needed) from its implementation. In other words, data abstraction
    separates the qualities of an object from the details of how it works.

  • Encapsulation = Hiding the
    implementation details of an object from the clients of the object.
    Encapsulation protects an object from unwanted access by clients.
    Encapsulating objects provides data abstraction; we can use them without
    knowing how they work.  Each object has an external view (its
    behavior) and an internal view (the state that accomplishes the behavior)

Reminder:
Every Java
class is part of a package, which is a collection of related classes that have
been released as a coherent unit (Example: the
Random class and the Scanner class are part of the java.util package, which is a
collection of general utility classes.) Whenever you refer directly to a class,
you must import the package in which it belongs. Java class libraries hold more
than 3000 pre-existing classes.
What if you need to create your own (user-defined) classes? You will learn how
to define your own classes and their methods, and how to create your own
objects from them.

Java
User-Defined Classes

Classes are used to create user-defined data types and implement Abstract
Data Types (ADTs). An ADT is an abstraction of a commonly appearing data
structure, along with a set of defined operations on the data structure. 
Historically, the concept of ADT in computer programming developed as a way of
abstracting the common data structure and the associated operations. Along the
way, ADT provided information hiding. That is, ADT hides the implementation
details of the operations and the data from the users of the ADT. Users can use
the operations of an ADT without knowing how the operations are implemented.
REMINDER: In Java classes are defined
in files with the .java
extension. The name of the file must match the name of the class defined within
it.

Here we will focus on user-created data types and understanding the
structure of a class is easiest in the context of specific examples. Suppose
that we want to create new user-defined data types to represent the time of
day, points in a xy coordinate system, and complex
numbers.

TYPE

 Time

STATE (DOMAIN)

 Each Time value is a time in hours, minutes, and
seconds.

BEHAVIOR (OPERATIONS)

 Set the time
 Return hours
 Return minutes
 Return seconds
 Display the time in standard format
 Display the time in military format
 Increment by one second
 Compare 2 times for equality
 Compare 2 times for < (determine if one time is “less than” or
“before” another time)
 Copy the time
 Get a copy of the time

 

TYPE

 Point

STATE (DOMAIN)

 Each point is an ordered pair of real numbers (x, y)
representing  the x and y coordinates

BEHAVIOR (OPERATIONS)

 Initialize the point
 Return the x coordinate
 Return the y coordinate
 Display the point
 Calculate distance from origin
 Compare 2 points for equality
 Shift location by a given amount (translate)
 Copy the point

 Get a copy of the
point

TYPE

 ComplexNumber

STATE (DOMAIN)

 Each complex number is an ordered pair of real numbers
(a, b) representing  a + bi, where i = sqrt(-1).

BEHAVIOR (OPERATIONS)

 Initialize the complex number
 Return the real part
 Return the imaginary part
 Display the complex number
 Add
 Subtract
 Multiply
 Divide
 Determine the absolute value of a complex number
 Compare 2 complex numbers for equality
 Copy the complex number

 Get a copy of a
complex number

Definitions, Syntax:

A class is a collection of a fixed number of components.  The
components of a class are called the members of the class.  The general
syntax for defining a class is

modifier(s)
class ClassName modifier(s){

     classMembers
}

where:

  • modifier(s) are used to alter the behavior of the class. Some
    modifiers are public, private, and static.
  • The word class is a reserved word in
    Java and it defines only a data type; no memory is allocated.
  • classMembers (also called entries)
    generally consist of named constants, variable declarations and/or
    methods.
    • If a member of a class
      is a named constant, you declare it just like any other named constant.

    • If a member of a class
      is a variable, you declare it just like any other variable. The
      (non-static) data members of a class are called instance variables (or fields).
    • If a member of a class
      is a method, you define it just like any other method. The methods of a
      class are called the instance methods
      of the class.
    • The methods that
      retrieve the value of an instance variable are called getters(also called accessor methods = methods that only access and
      do not modify the data members.) Names for getter/accessor
      methods usually begin with the prefix
      get.  The only
      exception is for getter methods that return a boolean, in which case the name typically
      begins with
      is.
    • The methods that change
      the value of an instance variable are called setters
      (also called mutator methods = methods that modify the data
      members (an object’s state.)) Names for
      setter/mutator methods usually begin with the
      prefix
      set.
    • A well-designed class
      uses private instance variables and mutator and
      accessor methods to implement the OOD principle
      of encapsulation.
    • The method members of a
      class can (directly) access any member of the class’ data members and
      methods. Therefore, when you write the definition of a method, you can
      directly access any data member of the class (without passing it as a
      parameter).
    • All entries in a Java
      class (method members or data members) are marked with one of the
      following access keywords (modifiers), to control which classes have
      access to that entry: private, public and protected.

public

All classes in the program have access
to any public entry. The public entries in a class are said to be exported by
that class. If a member of a class is public, you can access it outside the
class.

private

Access to entries declared as private
is limited to the class itself, making that entry completely invisible
outside the class. If a member of a class is private, you cannot access it
outside the class. 

protected

Protected entries are restricted
to the class that defines them, along with any of its subclasses or any
classes in the same package. 

(no modifier)

If the access keyword is missing,
the entry is visible only to classes in the same package. Such entries are
called package-private. 

NOTE #1: It is good practice to
make as many instance variables and methods private as is possible (information
hiding)
NOTE #2: In keeping with the modern
object-oriented conventions, in general, instance variables are declared as
private and instance methods are declared as public.
NOTE #3: In general, when you write
the definition of a method of a class and the method uses an object of that
class, then within the definition of the method the object can access its
private data members (in fact, any private member of the class.)
NOTE #4: Naming
conventions reminder (Java):
By convention, method names should be a
verb in lowercase or a multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc. In multi-word names, the first letter of
each of the second and following words should be capitalized. Here are some
examples: getStudentInfo, initializeMatrix,
compareTo, setMinutes, isEmpty, isFull, printArray.

NOTE #5: Typically, a method has a
unique name within its class. However, a method might have the same name as
other methods due to method overloading (see class constructors). Overloaded
methods should be used sparingly, as they can make code much less readable.

Class Constructors
 

·        
In
addition to the methods necessary to implement operations, every class has a
special type of method called constructors. A constructor has the same name as
the class, and it executes automatically when an object of that class is
created. Constructors are used to guarantee that the instance variables of the
class initialize to specific values.

·        
A
class constructor is a member method whose purpose is to initialize the private data members of a class object.

·        
A
constructor is implicitly invoked whenever a class object is declared/created
(never called!).
Invocation
of constructors: AUTOMATIC, according to the parameters passed.

·        
RULES
for designing and using class constructors:

  1. The name of a constructor is the same as the name of
    the class.
  2. A constructor has no return type (not even void!).
    Constructors cannot return a value.
  3. Constructors execute automatically when class objects
    are instantiated. Because they have no types, they cannot be called like
    other methods. COMMON ERROR: Trying to reset an object by calling a
    constructor. Constructors are NEVER called!
  4. Classes may include several constructors –>
    Constructors of a class can be overloaded.
  5. Any two constructors must have different signatures
    (different parameter lists.) If there are multiple constructors, the
    constructor that executes depends on the type of values passed to the
    class object when the class object is instantiated.
  6. Constructor with no parameters = default constructor
    (implicitly invoked.)
  7. The parameter list appears after declaration — if
    there are parameters, their values are listed in parentheses in the declaration.
    Example:

someClass someClassObject = new someClass(parameter1,
parameter2, … )

NOTE #6:
If you do not include ANY constructor in a class, then Java automatically
provides the default constructor. If you provide at least one alternate
constructor without providing the default constructor, then Java will NOT
automatically provide the default constructor.
NOTE #7: In
a class definition, it is a common practice to list all the instance variables,
named constants, other data members, or variable declarations first, then the
constructors, and then the methods.

Variable Declaration and
Object Instantiation:
by using ordinary variable declaration with the
operator new (an
object is an instance of a class and the operator new is used to instantiate the object).

Reminder: 2
types of variables in Java — primitive type variables (store data directly
into their own memory space) and reference variables (store the address of the
object containing the data).

Important NOTE: The operator new causes the system
to allocate memory space of a specific type, store specific data in that memory
space, and return the address of that memory space. In Java, reference
variables store the address of a memory space. In Java, any variable of type class is a reference
variable. In other words, any object (or instance of the class) is a reference
variable. Using the operator new
to create a class object is called an instantiation of that class. When working
with classes, we actually declare  a reference
variable of a class
type and then, using the operator new we instantiate an object of that class type and store
the address of the object  into the reference variable.

·        
Once
a class is defined, you can create objects of that class. Whenever  we declare an object of a class we declare a
reference variables of that class type.

·        
Object
declaration implies:

  1. Declaration of a reference variable of type class.
  2. Instantiation of  the
    class object.
  3. Storage of  the address
    of the object into the reference variable declared.

·        
In
order to allocate memory space for the variable the operator
new is used as follows:

new
className()

OR

new
className(param1, param2, …, paramN)

·        
The
first statement instantiates the object and initializes the instance variables
of the object using the default constructor. The second statement instantiates
the object and initializes the instance variables using a constructor with
parameters (alternate constructor.)  The number of actual parameters and
their type should match the formal parameters (in the order given) of one of
the constructors.  If the types don’t match the formal parameters of any
constructor (in the order given), Java uses type coercion and looks for the
best match.

·        
Example:
Create 2 new
objects of the
Time
class.

Time startTime = new Time();//
default constructor invoked, no parameters

//What happened: startTime
declared as a reference variable of type Time and hrs,
mins, secs initialized with

//Object startTime
accessed via the reference variable startTime

Time
endTime = new Time(19,30,10);// alternate constructor invoked, parameterized
constructor

//What
happened: endTime declared as a reference variable of
type Time and hrs, mins, secs initialized with 19, 30, 10

//Object
endTime accessed via the reference variable endTime

Additional
Resources:

1. (Sun) API specification for version 6 of the Java Platform, Standard
Edition: http://java.sun.com/javase/6/docs/api/

2. (Sun) The Java Tutorials, Classes and Objects: http://java.sun.com/docs/books/tutorial/java/javaOO/index.html

References:
[1] Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison
Wesley, 2008.
[2] Java Programming: From Problem Analysis to Program Design, by D.S. Malik,
Thomson Course Technology, 2008
 


View more information: http://orion.towson.edu/~izimand/237/LectureNotes/1-Lecture-Classes-1.htm

See more articles in category: Best
READ:  What Is A Sentence? | Grammar

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button