Lecture 4: Object-Based
Programming
What You Will Learn Today
- Define and give examples of objects, classes, fields
and methods.
- Define and give examples of class libraries, APIs and
packages.
- Explain the use of the
import
declaration.
- Declare, define and use fields and methods.
- Differentiate field and method access control
qualifiers (
public, private, protected
).
- Create class fields and methods using the
static
modifier.
- Put the features of a class definition in a consistent
sequence.
- List steps to design a class.
- object
- representation of a specific person, thing or concept; usually named with a noun in
English
an instance of a class; has attributes and methods; first letter is
small
e.g. a specific tree, dog, person, student, car, ball, coin, book, bankAccount, string, array, rectangle, matrix, errorMessage
- class
- a blueprint, template, model, pattern or factory to produce objects with similar
features, usually a singular noun, first letter is capitalized
e.g. all tree objects belong to the class Tree; all people belong to the class
Person
- field or attribute
- a variable that represents the object's state, that
stores information about an object (properties and characteristics)
e.g. a person's name, birthdate, address and phone number; a ball's position,
diameter and colour
- method
- a function that represents an object's behaviour; usually
named with a verb in English
(something the object can do, or something that can be done to or with
the object)
e.g. throw, bounce or roll a ball; deposit or withdraw money from a bank
account; calculate a person's age
Examples of Classes and Objects
System.out.println("Hello, World!");
System is a class; out is an object stored within the class; print() and
println() are methods.
String name = new String ("Michel Lejeune"); int len = name.length();
String is a class; name is an object; length() is a method which returns the
length of the string.
float a = Math.PI * r * r; int n = (int)(Math.random() * 100) + 1;
Math is a class, PI is a constant field, and random() is a class method
which returns a random number.
- class library
- a set of reusable classes which supports development of programs
e.g. the Java standard class library
- Application Programmer Interface (API)
- group of related classes
e.g. the Java database API for databases, Swing for graphical user interfaces
- package
- group of related classes with a structured name
e.g. java.lang (language support); java.io (input/output); java.util
(utilities);
java.awt (graphics and GUI);
- javax.swing (GUI); java.applet (applets); java.net (networking); java.sql
(database access)
- To use objects from most APIs or packages you need to either import
or use fully qualified names (package.class)
- e.g. to throw an IOException you need to put the following line at the
beginning, before the class definition:
import java.io.IOException;
- Otherwise you would have to use the fully qualified name, e.g.
throws java.io.IOException
- The Keyboard class is not part of the Java standard class library.
To use it, import it or use the fully qualified name, e.g.
- to read an integer by importing:
import cs1.Keyboard;
class MyClass { ... int i = Keyboard.readInt(); ... }
- to read an integer by using the fully qualified name:
class MyClass { ... int i = cs1.Keyboard.readInt(); ... }
java.lang
is automatically imported into all Java
programs
- e.g. String and System objects can be used without an import statement;
you do not have to type
import java.lang.*;
- Instance fields belong to a single object and are declared inside a
class but after all method definitions.
- Instance fields can be assigned and used inside any method of the class.
- e.g. In the Point class below, x and y are instance
fields, initialised by the Point() constructor methods, used by getX() and
getY() methods.
Defining Methods
- Methods have a qualifier, a return type, 0 or more
parameters in parentheses, and a body in braces which includes a
return statement.
- e.g.
public String getName () { return name; }
- Each parameter has a type. All parameters are passed by value; the scope
ends when returning from the method.
- Methods that do not return anything have a return type of void and
should use return without an value.
- e.g.
public static void doNothing () { return; }
Calling Methods
- An instance method is attached to a specific object and accessed by
using
objectName.methodName
()
.
- To call an instance method, use
objectName
.methodName()
- e.g.
String myString = "Hello"; int i = myString.length();
// myString is an object with method length()
Constructor Methods
- A constructor method is defined using the same name as the class,
with no type declaration.
e.g. class Tree { Tree() { ... } ... }
- There can be more than one constructor method for the same class as long
as they have different numbers or types of arguments, e.g.:
class Circle { Circle() {...} Circle(int r) {...}
Circle(float r, float x, float y) {...} }
- Overloading is using the same name for more than one method or
constructor.
- A constructor method is called (invoked or used) when a new object
is created with the new keyword.
e.g. String myString = new String("Hello");
- When a new object is created, space is allocated in memory for the
object's fields, and the fields are initialised.
- If a constructor method is supplied, other actions can be performed;
otherwise only the default constructor is performed.
public
fields are available to any class.
private
fields are only available to methods of the
class.
- Encapsulation is hiding implementation details by declaring them
private
;
it is a key advantage of object-based programming.
protected
fields are available to methods of the
class and subclasses (discussed later in the inheritance lecture).
- Tip: Declare all fields as either
private
or
public
. Use public
only for final
variables.
- For access by other classes to
private
variables, create
accessor and mutator methods like getVariable()
and setVariable()
.
- e.g.
w = rectangle.getWidth();
// instead of w =
rectangle.width;
- e.g.
rectangle.setWidth(w);
// instead of rectangle.width
= w;
Access Control for Methods
public
methods are available to any other class.
public
methods are used by outside objects to communicate with the object.
private
methods are available only to other methods in the class.
private
methods encapsulate the internal implementation of the class;
they hide the
messy details from outside objects.
protected
methods are available to objects in the class and any
subclass.
- If you do not use
public
, private
or
protected
, the
method will be available to any object in the package.
- Tip: Methods should be either
public
or private
(except in
rare cases).
- Class fields are shared by all objects in a class;
they belong to the class, not a single object.
- Class variables can be used to communicate between
objects of a class.
- A class field is declared with the static keyword.
- e.g.
static int objectCount = 0;
// counts the
number of objects of that type that have been created
- Tip: Avoid using class variables that can change,
because they are often accidentally overwritten.
static
constants (final
variables)
are common, useful and often made public
.
- e.g.
public static final double VAT = 0.17;
Class Methods
- A class method is a method not attached to a specific object and
accessed by using
ClassName
.methodName()
.
- A class method is declared with the
static
keyword.
- e.g.
public static double sin (double x) { ... }
- Standard library examples include most of the Math methods which perform calculations, e.g.
Math.random()
, Math.sin(x)
.
- class comment explaining the purpose of the class
- class name and qualifiers
- class body: put all public features before all private features; each
should include:
- methods (separated by a blank line)
- constructors
- instance methods
- static methods
- fields
- instance fields
- static fields
- inner classes (hidden classes only declared and used within a class)
/**
a double precision point in two dimensional geometry, with two coordinates (x, y)
*/
public class Point
{
public Point() { x = 0; y = 0; }
public Point(double xx, double yy) { x = xx; y = yy; }
public double getX() { return x; }
public double getY() { return y; }
private double x;
private double y;
}
- Find out what the objects of the class should be able to do.
- Use verbs to describe actions.
- Choose names for the methods.
- Document the public interface.
- Abstraction is finding the essential features of a class, and
leaving out extra details.
- Determine instance variables.
- Determine constructors.
- Implement methods.
- Test the class with a test program.
- It is often a good idea to have a Test class with a
main()
method to check if your class is
working.
e.g. instead of having a main()
method inside Point
,
put main()
in another class named PointTest
.
- The original class can then be reused by many other programs rather than
being tied to a
main()
method.
To Do After Class
-
Project 1 Proposal is due
Friday. Look at the program ideas, select
a topic, write your proposal, and e-mail it to the
lecturer.
-
Read Big Java Ch. 2 and 7, or another introduction to object-based programming
in Java.
-
Homework 2 is due next week.