Topic 8 Classes, Objects and Methods 1
Topic 8
Class and Method Definitions Information Hiding and Encapsulation Objects and Reference
Classes, Objects, and Methods
Topic 8 Classes, Objects and Methods 2
OO revision Objects
» A capsule that contains 2 important parts– State (attributes or data)
What does the object know?– Behaviour (methods or functions)
What does the object know how to do?» E.g. Cars, employee records, etc.
Class» is the definition of a kind of object (template for creating objects).» E.g. a general description of what an automobile is and what it can do» Encapsulates values & operations on those values.» Also used to group related methods, like the Math class.
Instantiate» An object that satisfies the class definition is said to instantiate the class.
Topic 8 Classes, Objects and Methods 3
Class Definition
Class Name: Car
Data:
amount of fuel
speed
license plate
Methods (actions):
increase speed:
How: Press on accelerator pedal
stop:
How: Press on brake pedal
Topic 8 Classes, Objects and Methods 4
General class syntax:
modifier(s) class ClassIdentifier{classMembers
}
Modifier(s)» Used to alter the behaviour of the class» public, private, static
ClassMembers» Named constants, variable declarations and/or methods» Can also be declared as public, private or static
Topic 8 Classes, Objects and Methods 5
class Car
{
double fuelAmount = 0.0;
double speed = 0.0;
String licencePlate = “ “;
}
Topic 8 Classes, Objects and Methods 6
Instantiations of the Class Car
amount of fuel: 10 litres
speed: 55 km / hr
licence plate: “135 XJK”
amount of fuel: 14 litres
speed: 0 km /hr
licence plate: “SUES CAR”
First InstantiationObject name: patsCar
Second InstantiationObject name: suesCar
Third InstantiationObject name: ronsCar
amount of fuel: 2 litres
speed: 75 km / hr
licence plate: “351 WLF”
Topic 8 Classes, Objects and Methods 7
Car Example
Car Class» Says Car objects has 3 pieces of data (i.e. specifies what kind of data
they have.– (litres of fuel in tank; how fast car is moving; license plate)
» Class definition has no data individual objects have the data.
» Also specifies what actions (methods) the objects can take & how they accomplish those actions.– increaseSpeed – stop
» All objects of the Car class have the exact same methods.
Topic 8 Classes, Objects and Methods 8
Car Example continued…..
Car Object» Instantiates the Car class.» Each object has a name these are variables of type Car.
– patsCar, suesCar, ronsCar
Topic 8 Classes, Objects and Methods 9
Types of methods
Every method belongs to a class. Method definitions given inside the definition of the class.
Single value methods» Used to return Java values
Void-methods» Performs some action rather than return a value.» Used to produce Java statements.» E.g. print a message or read in a value from the keyboard) and do
not return a value
Topic 8 Classes, Objects and Methods 10
Single-value Method Definitions:
public Type_Returned Method_Name(parameters){ list of statements must contain a return statement}
public double getFuelAt(){
return fuelAmount;}
Topic 8 Classes, Objects and Methods 11
void Method Definitions:
public void Method_Name(parameters) HEADING{ list of statements BODY}
public void writeOutput(){
System.out.println(“License: “ + licence); System.out.println(“Fuel: “ + fuelAmount);
System.out.println(“Speed: “ + speed);return; Can be left out
}
Topic 8 Classes, Objects and Methods 12
PARAMETERS
Formal parameters» Used in the method definition
Actual parameters» Value of the variable that is passed to the
method when that method is called/invoked.
Topic 8 Classes, Objects and Methods 13
Method invocation / Call a method
Object_name.method_name();
Method defined in a class is usually invoked using an object of that class object calling a method
Topic 8 Classes, Objects and Methods 14
CONSTRUCTORS: Special type of method .
» Not void » Does not return a value
One or more found in every class.
Has the same name as the class & it executes automatically when an object of that class is created.
Used to guarantee that the instance variables of the class are initialised to specific values.
Types of constructors» With parameters» Without parameters (known as the default constructor)
Topic 8 Classes, Objects and Methods 15
Instantiating / Constructing Objects
To instantiate an object, use the keyword new followed by the class’s constructor method (creates a new instance of a class).
Car patsCar; // creates a new Car variable
c = new Car(); // invokes the constructor method
or
Car patsCar = new Car();
Topic 8 Classes, Objects and Methods 16
The Member Access Separator
Once you’ve constructed a car, you want to do something with it. To access the fields or methods of the car you use the . (dot) separator.
» Selects a specific member of a Car object by name.
Car patsCar = new Car();
patsCar.fuelAmount = 10.0;
patsCar.speed = 55.0;
patsCar.licencePlate = “135XJK “;
System.out.println(c.licencePlate +
“ is moving at “ + patsCar.speed + “ kms/hr”);
Topic 8 Classes, Objects and Methods 17
Class file REMINDERS
Each Java class definition should be a separate file Use the same name for the class and the file, except add ".java"
to the file name For now put all the classes you need to run a program in the
same directory
Topic 8 Classes, Objects and Methods 18
Standard methods for a class Constructor methods
» Methods which initialise the object when it is first created.
Reader / Get methods» Methods which allow outside codes to view or get copies of the object’s
state.
Writer / Set methods» Methods which allow outside codes to assign new values for the object’s
state.
Mutator methods» Methods which allow outside codes to modify the state of an object.
Query methods» Methods which test the state of an object.
Topic 8 Classes, Objects and Methods 19
class Car
{
double fuelAmount = 0.0;
double speed = 0.0;
String licencePlate = “ “;
void setMaxSpeed()
{
speed = 200.0;
}
}
Topic 8 Classes, Objects and Methods 20
SIMPLE CLASS EXERCISE!!! Consider a simple class of objects which represent Rectangles. A brief (&
shallow) analysis will reveal the state & behaviour of our simple Rectangle objects.
The state (knows its?)» length (integer)» width (integer)
The behaviour (knows how to?)» Initialise itself» Set its length» Set its width» Return its width» Return its length» Calculate its area» Calculate its perimeter
Topic 8 Classes, Objects and Methods 21
// File: Rectangle.java
// A class which specifies simple Rectangle objects
// Note that NONE of the members of Rectangle class
// are labelled 'static'
class Rectangle
{
// State (data variables)
private int length;
private int width;
Topic 8 Classes, Objects and Methods 22
// Behaviour (instance methods)
// Constructor
public Rectangle()
{
length = 0;
width = 0;
}
Topic 8 Classes, Objects and Methods 23
// Writer or Set methods
public void setLength( int len )
{
length = len;
}
public void setWidth( int wid )
{
width = wid;
}
Topic 8 Classes, Objects and Methods 24
// Reader or Accessor methods
public int getLength()
{
return length;
}
public int getWidth()
{
return width;
}
Topic 8 Classes, Objects and Methods 25
// Other services
public int area() {
int the_area = length * width; return the_area;
}
public int perimeter() {
int perim; perim = 2 * (length + width); return perim;
}
Topic 8 Classes, Objects and Methods 26
public boolean isLegal()
{
if( length >= 0 && width >= 0 )
return true;
else
return false;
}
}// end class
Topic 8 Classes, Objects and Methods 27
Constructor Methods Must have same name as the class. Does not have any return type
» Not even void
Creates a new instance of the class.» Initialises all the variables & does any work necessary to prepare the
class to be used.
If no constructor is exists, Java provides a generic one that takes no arguments.» Better to write your own constructor.
Topic 8 Classes, Objects and Methods 28
Can have several constructor methods.» Each constructor method must have a different header
– Parameter list» Also known as overloading methods.
// another constructor
public Rectangle(int len, int wid)
{
length = len;
width = wid;
}
Topic 8 Classes, Objects and Methods 29
Access Control
public» Variable or method is available to other programs.
private» To protect variable from external modification» No other code outside this class can directly access these variables
or methods.» i.e. If you want objects in the same class to be able to get or set the
value of a field or invoke a method.
protected» If you want access restricted to subclasses & members of the same
package.
Topic 8 Classes, Objects and Methods 30
Instance / Non-static Methods
None of the methods in the Rectangle class are labelled static.
These types of methods are designed to be accessed via objects.
Topic 8 Classes, Objects and Methods 31
NB!! NB!! NB!!
The Rectangle source file must be compiled.» Note that the Rectangle.java file is not a program (no
main method) – you can’t run it.
To use this Rectangle class, you have to write another program which does have a main method.» Driver program / Client code» In this program you can create Rectangle objects and call
methods in those objects.
The Rectangle program and its driver program must both be compiled in the same directory.
Topic 8 Classes, Objects and Methods 32
Testing Rectangles (Driver program)
class RectTest
{
public static final void main(String[] args)
{
Rectangle page = new Rectangle();
page.setLength(30);
page.setWidth(21);
System.out.println(“The rectangle has a length of”);
System.out.println(page.getLength());
System.out.println(“and a width of “);
System.out.Println(page.getWidth());
Topic 8 Classes, Objects and Methods 33
System.out.println(“It’s area is “);
System.out.println(page.area());
System.out.println(“It’s perimeter is “);
System.out.println(page.perimeter());
} //end main
} // end class
Topic 8 Classes, Objects and Methods 34
Encapsulation» All data & methods of Rectangles encapsulated.
– Hidden the data from outside use» Provides protection of the data from malicious access
Public Interface» Methods are all public a.k.a. the public interface to Rectangles.
» Only way to deal with Rectangle objects is through their (public) methods.