Anda di halaman 1dari 62

Classes and Objects

Zahid Aslam

Overview

Implementing classes and objects in Java.

Understand important features in Java classes.

Visibility Control

Static Methods and Attributes

Parameter Passing

Object Delegation

Object Cleanup
Zahid Aslam

Classes

A class is a collection of fields (data or attributes) and methods


(procedure or function) that operate on that data.

Circle
centreX
centreY
radius
area()
circumference()

Zahid Aslam

Defining a Class

The basic syntax for a class definition:


class ClassName [extends SuperClassName]
{
[fields declaration]
[methods declaration]
}

Bare bone class :


// Circle.java
// Circle class definition
class Circle {
}
Zahid Aslam

Adding Fields: Class Circle with


fields

Add fields
// Circle.java
class Circle {
double centreX, centreY; //centre coordinate
double radius;
//radius
}

The fields (data) are also called the instance variables.

Zahid Aslam

Adding Methods

A class with only data fields are not useful. Objects created by
such a class cannot respond to any messages.
Methods are declared inside the body of the class but
immediately after the declaration of data fields.
The general form of a method declaration is:

type methodName (parameter-list)


{
method-body;
}

Zahid Aslam

Circle Class - Example


// Circle.java
class Circle {
double centreX, centreY;
double radius;
//Methods to return circumference and area
double circumference() {
double circum = 2*3.14*radius;
return circum;
}
Method Body
double area() {
double area = 3.14 * radius * radius;
return area;
}
}
Zahid Aslam

Compiling the class

Create a file Circle.java and enter the code for the class
shown in the previous example (Note: the file name
should match the class name).

Compiling the class :


javac Circle.java
Creates file Circle.class

Circle becomes a derived data type that can be


used in a java program.

Zahid Aslam

Data Abstraction

Declaring the Circle class, has created a new data type Circle
Data Abstraction

Variables of the data type can be now defined in a program.


// CircleTest.java
// Test program to test the Circle class
class CircleTest {
public static void main( String args[] ) {
Circle aCircle;
Circle bCircle;
}
}
Zahid Aslam

Class of Circle cont.

The definitions: Circle aCircle; Circle bCircle; in the above


example did not create Circle objects.

aCircle, bCircle are simply references to a Circle object, not an


object itself.

aCircle

bCircle

null

null

Points to nothing
(Null Reference)

Points to nothing
(Null Reference)

Zahid Aslam

Creating objects of a class

Objects are created dynamically using the new keyword.

aCircle and bCircle refer to Circle objects

aCircle = new Circle();

bCircle = new Circle();

Zahid Aslam

Creating objects of a class


// CircleTest.java
// Test program to test the Circle class
class CircleTest {
public static void main( String args[]){
Circle aCircle;
Circle bCircle;
aCircle = new Circle();
bCircle = new Circle();
}
}

Zahid Aslam

Creating objects of a class


aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;

Before Assignment

Before Assignment

aCircle

bCircle

aCircle

bCircle

Zahid Aslam

Automatic garbage collection

The object Q
used in future.

does not have a reference and cannot be

The object becomes a candidate for automatic garbage


collection.

Java automatically collects garbage periodically and releases


the memory used to be used in the future.

Zahid Aslam

Accessing Variables and


Methods

Similar to C syntax for accessing data defined in a structure.

ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();


// initialize centre and radius
aCircle.centreX = 2.0;
aCircle.centreY = 2.0;
aCircle.radius = 1.0;
Zahid Aslam

Executing Methods in
Object/Circle

Using Object Methods:

sent message to aCircle

Circle aCircle = new

Circle();

double area;
area = aCircle.area();

Zahid Aslam

Using Circle Class - Example


// CircleTest.java
class CircleTest {
public static void main(String args[]){
Circle aCircle;
aCircle = new Circle();
aCircle.centreX = 10;
aCircle.centreY = 20;
aCircle.radius = 5;
double area = aCircle.area();
double circumf = aCircle.circumference();
System.out.println(
"Radius="+aCircle.radius+" Area="+area);
System.out.println("Radius="+
aCircle.radius+"Circumference ="+circumf);
}
}
Zahid Aslam

Using Circle Class - Example

Program Output :

Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002

Zahid Aslam

Better way of Initialising or


Access Data Members x, y, r

Information Hiding is important!


Avoid giving direct access to attributes.
Define Access methods.
an interface for the rest of the system to use.
To initialise/Update a value:
aCircle.setX( 10 )
To read a value:
aCircle.getX()
These methods are informally called as Accessors or
Setters/Getters Methods.

Note : Java text book uses a different convention from what is


used in these notes. Get method in the text book is
equivalent to set method in these examples.
Zahid Aslam

Accessors Getters/Setters
// Circle.java
class Circle {
double centreX, centreY, radius;
//Methods to set and get fields
double getX() { return centreX;}
double getY() { return centreY;}
double getR() { return radius;}
void setX(double x_in) { centreX = x_in;}
void setY(double y_in) { centreY = y_in;}
void setR(double r_in) { radius = r_in;}
// Other methods go here
}

Zahid Aslam

Using get/set methods Example


// CircleTest.java
class CircleTest {
public static void main(String args[]){
Circle aCircle;
aCircle = new Circle();
aCircle.setX(10);
aCircle.setY(20);
aCircle.setR(5);
double area = aCircle.area();
double circumf = aCircle.circumference();
System.out.println(
"Radius="+aCircle.getR()+" Area="+area);
System.out.println("Radius="+
aCircle.getR()+"Circumference ="+circumf);
}
}
Zahid Aslam

Object Initialization

When objects are created, the initial value of data fields is


unknown unless its users explicitly do so.

In the previous examples the initial values were set after


object creation using syntax:
ObjectName.DataField1 = 0;
ObjectName.SetDataField1(0);

In many cases, it would be useful if this initialisation can


be carried out by default without the users explicitly
initializing them.

In Java, this can be achieved through a mechanism called


constructors.
Zahid Aslam

What is a Constructor?

Constructor is a special method that is invoked


automatically at the time of object creation.

Constructor is normally used for initializing objects with


default values unless different values are supplied.

Constructor has the same name as the class name.

Constructor cannot return values.

A class can have more than one constructor as long as


they have different input arguments - Overloading

There is NO explicit invocation statement needed: When


the object creation statement (new) is executed, the
constructor method will be executed automatically.
Zahid Aslam

Defining a Constructor
public class ClassName {
// Data Fields
// Constructor
ClassName() {
// Method Body Statements
}
//Methods to manipulate data fields
}

Zahid Aslam

Adding a Constructor to Circle


class: Example
// Circle.java
class Circle {
double centreX, centreY, radius;
Circle() {
centreX = 0;
centreY = 0;
radius = 10.0;
}
//Methods to set and get fields
// Other methods go here
}
Zahid Aslam

Adding a Multiple-Parameters
Constructor to our Circle Class
class Circle {
double centreX, centreY, radius;
// Constructor
Circle(double x, double y, double r)
{
centreX = x;
centreY = y;
radius = r;
}
//Methods to set and get fields
// Other methods go here
}

Zahid Aslam

Constructors initialise Objects

Recall the following OLD Code Segment:

Circle aCircle = new Circle();


aCircle.x = 10.0;
aCircle.y = 20.0
aCircle.r = 5.0;
aCircle=newCircle();
At creation time the center and radius
are not defined.
These values are explicitly set later.

Zahid Aslam

Constructors initialise Objects

With defined constructor

Circle aCircle = new Circle(10.0, 20.0, 5.0);

aCircle = new Circle(10.0, 20.0, 5.0);

aCircle is created with center (10, 20)


and radius 5
Zahid Aslam

Constructor Test - Example


// CircleConstructorTest.java
class CircleConstructorTest {
public static void main(String args[]){
Circle aCircle = new Circle(10.0, 20.0, 5.0);
System.out.println(CentreX=+aCircle.getX());
System.out.println(CentreY=+aCircle.getY());
System.out.println("Radius="+aCircle.getR());
}
}
Program Output : CentreX=10.0
CentreY=20.0
Radius=5.0
Zahid Aslam

Multiple Constructors

Sometimes want to initialize in a number of different ways,


depending on circumstance.

This can be supported by having multiple constructors


having different input arguments.

Zahid Aslam

Multiple Constructors
class Circle {
double centreX, centreY, radius;
// Constructor
Circle(double x, double y, double r){
centreX = x; centreY = y; radius = r;
}
Circle(double r){
centreX = 0.0; centreY = 0.0; radius =
r;
}
Circle(double x, double y){
centreX = x; centreY = y; radius =
10.0;
}
//Methods to set and get fields
// Other methods go here
Zahid Aslam
}

Initializing with constructors


public class TestCircles {
public
Circle
Circle
Circle
}

static void main(String args[]){


circleA = new Circle(10.0, 12.0, 20.0);
circleB = new Circle(10.0);
circleC = new Circle(5.0,10.0);

circleA = new Circle(10, 12, 20) circleB = new Circle(10)circleC = new Circle(5,10)

Centre = (10,12)
Radius = 20

Centre = (0,0)
Radius=10

Centre = (5,10)
Radius = 10

Zahid Aslam

Method Overloading

Constructors all have the same name.


Methods are distinguished by their signature:
name
number of arguments
type of arguments
position of arguments

That means, a class can also have multiple methods with the
same name : method overloading. This is a form of
polymorphism.

Not to confuse with method overriding (coming up).

Zahid Aslam

Polymorphism

Allows a single method or operator associated with different


meaning depending on the type of data passed to it. It can be
realised through:
Method Overloading

Defining the same method with different argument types


(method overloading) - polymorphism.

The method body can have different logic depending on the


date type of arguments.

Zahid Aslam

The New this keyword


this keyword can be used to refer to the object itself. It is
generally used for accessing class members (from its own
methods) when they have the same name as those passed
as arguments.

class Circle {
double centreX, centreY, radius;
// Constructor
Circle (double centreX, double centreY, I
double radius) {
this.centreX = centreX;
this.centreY = centreY;
this.radius = radius;
}
// Other methods
}
Zahid Aslam

Visibility Control: Data Hiding and


Encapsulation

Java provides control over the visibility of variables and


methods.

This allows encapsulation, which is safely sealing data within


the capsule of the class.

Prevents programmers from relying on details of class


implementation, so you can update without worry.

Helps in protecting against accidental or wrong usage.

Keeps code elegant and clean (easier to maintain).

Zahid Aslam

Visibility
Circle

Construction time message

Circle
area
messag
e

Center (x,y)
Radius r

circumference

message

Zahid Aslam

Visibility Modifiers: Public,


Private, Protected

Public keyword applied to a class, makes it available/visible


everywhere. Applied to a method or variable, completely
visible.
Default (No visibility modifier is specified): it behaves like
public in its package and private in other packages.

Private fields or methods for a class only visible within that


class. Private members are not visible within subclasses, and
are not inherited.

Protected members of a class are visible within the class,


subclasses and also within all classes that are in the same
package as that class. They are also visible to subclasses in
other packages.

Zahid Aslam

Visibility
public class Circle {
private double centreX, centreY, radius;
// Constructor
public Circle (double x, double y, double r)
{
this.x = x;
this.y = y;
this.r = r;
Circle
}
public double circumference(){
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}

-centreX
-centreY
-radius
+area()
+circumferenc
Zahid Aslam

Accessors Getters/Setters
public class Circle {
private double x,y,r;
//Methods to return circumference and
public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public void setX(double x) { this.x =
public void serY(double y) { this.y =
public void setR(double r) { this.r =

area

x;}
y;}
r;}

More on Visibility during Inheritance and Package Discussion

Zahid Aslam

Static Members

Java supports definition of global methods and attributes that


are common to all objects of the type of class. Such members
are called Static members.

An attribute or a method can be defined to be static.

This feature is useful when we want to create a variable


common to all instances (objects) of a class.

One of the most common examples of a static attribute is one


that keeps count of the number of objects of the class that
have been created.

Note: Java creates only one copy for a static variable which
can be used even if the class is never instantiated.
Zahid Aslam

Static Variables - Example


// Cricle.java
class Circle {
// static (class ) variable
// One for the Circle class, number of circles
static int numCircles = 0;
double centreX, centreY, radius;
// Constructors and other methods
Circle(double x, double y, double r){
centreX = x; centreY = y; radius = r;
numCircles++;
}
}
Zahid Aslam

Using Static Variables Example


// CountCircles.java
class CountCircles {
public static void main(String args[]){
Circle circleA = new Circle( 10, 12, 20);
I
// numCircles = 1
System.out.println(Number of Circles

= +

Circle.numCircles );
Circle circleB = new Circle( 5, 3, 10);
// numCircles = 2
System.out.println(Number of Circles = +
Circle.numCircles );
}
Zahid Aslam

Static Variables - Example

Program output:
Number of Circles
Number of Circles

= 1
= 2

circleA = new Circle(10, 12, 20)

numCircl
es

circleB = new Circle(5, 3, 10)

Zahid Aslam

Instance Vs Static Variables

Instance variables : One copy per object. Every object


has its own instance variable.
E.g. centreX, centreY, radius (centre and radius in
the circle)

Static variables : One copy per class.


E.g. numCircles (total number of circle objects created)

Zahid Aslam

Static Methods

A class can have methods that are defined as static (e.g., main
method).

Static methods can be accessed without using objects. Also,


there is NO need to create objects.

They are prefixed with keyword static

Static methods are generally used to group related library


functions that dont depend on data members of its class. For
example, Math library functions.

Zahid Aslam

Static methods restrictions

Static methods can only call other static methods.


Static methods can only access static data.
Static methods cannot refer to this or super (more later) in
anyway.

Zahid Aslam

Static Methods - Example


// Circle.java
class Circle {
// static (class ) variable
// One for the Circle class, number of circles
private static int numCircles = 0;
private double centreX, centreY, radius;
// Constructors and other methods
public Circle(double x, double y, double r){
centreX = x; centreY = y; radius = r;
numCircles++;
}
public static void printNumCircles(){
System.out.println(NumCircles=+numCircles);
}
}

Zahid Aslam

Using Static Methods Example


// CountCircles.java
class CountCircles {
public static void main(String args[]){
Circle circleA = new Circle( 10, 12, 20);
Circle circleB = new Circle( 5, 3, 10);
Circle.printNumCircles();
}
}Program Output:
NumCircles=2
Zahid Aslam

Back to HelloWorld
[System invokes static main
method]
// HelloWorld.java:
Hello World program
class HelloWorld
{
public static void main(String args[])
{
System.out.println(Hello World);
}
}

Zahid Aslam

Back to Constants
[final can also be made as static]
// SquaredNumbers.java
class SquaredNumbers{
static final int MAX_NUMBER = 25;
public static void main(String args[]){
final int MAX_NUMBER = 25;
int lo = 1;
int squared = 0;
while (squared <= MAX_NUMBER){
squared = lo * lo;
System.out.println(squared);
lo = lo + 1;
}
}
}
Zahid Aslam

Final

A java variable can be declared using the keyword final. Then


the final variable can be assigned only once.
A variable that is declared as final and not initialized is called a
blank final variable. A blank final variable forces the
constructors to initialise it.
Java classes declared as final cannot be extended. Restricting
inheritance!
Methods declared as final cannot be overridden. In methods
private is equal to final, but in variables it is not.
final parameters values of the parameters cannot be
changed after initialization. Do a small java exercise to find out
the implications of final parameters in method overriding.
Java local classes can only reference local variables and
parameters that are declared as final.
A visible advantage of declaring a java variable as static final
is, the compiled java class results in faster performance.

Zahid Aslam

Parameter passing

Method parameters which are objects are passed by


reference.

Copy of the reference to the object is passed into method,


original value unchanged.

Zahid Aslam

Parameter passing - Example


// ReferenceTest.java
public class ReferenceTest {
public static void main (String[] args)
{
Circle c1 = new Circle(5, 5, 20);
Circle c2 = new Circle(1, 1, 10);
System.out.println(c1 Radius =
+c1.getR());
System.out.println(c2 Radius =
+c2.getR());
parameterTester(c1, c2);
System.out.println(c1 Radius = +c1.getR());
System.out.println(c2 Radius = +c2.getR());
}

........ cont
Zahid Aslam

Parameter passing - Example


public static void parameterTester(Circle
circleA,
Circle circleB)
{
circleA.setR(15);
circleB = new Circle(0, 0, 100);
System.out.println(circleA Radius= +
circleA.getR());
System.out.println(circleBRadius= +
circleB.getR());
}
}

Zahid Aslam

Parameter passing - Example

Program Output :

c1 Radius = 20.0
c2 Radius = 10.0
circleA Radius = 15.0
circleB Radius = 100.0
c1 Radius = 15.0
c2 Radius = 10.0

Zahid Aslam

Parameter passing - Example


STEP1 Before calling
parameterTester()
c1

c2

circleA (5,5,20) circleB (1.1,10)


X

STEP2 parameterTester(c1, c2)


c1

c2

circleA (5,5,20) circleB (1.1,10)

STEP3
circlA.setRadius(15)
c1
c2

circleA (5,5,15) circleB (1.1,10)

STEP4 circlB = new


Cirlce(0,0,100)
c1
c2

circleA (5,5,15) circleB (1.1,10)

Zahid Aslam
(0.0,100)

Parameter passing - Example


STEP5 After Returning from parameterTester
c1

c2

circleA (5,5,15) circleB (1.1,10)


X

Zahid Aslam

Delegation/Association

Ability for a class to delegate its responsibilities to another


class.

A way of making an object invoke services of other objects


through containership.

Zahid Aslam

Delegation - Example
class Point {
private double xCoord;
private double yCoord;
// Constructor
.
public double getXCoord(){
return xCoord;
}
public double getYCoord(){
return yCoord;
}

Point
xCoord
yCoord
getXCoord()
getYCoord()

Zahid Aslam

Delegation - Example
public class Circle {
private Point centre;
public double getX(){
return centre.getXCoord();
}
public double getY(){
return centre.getYCoord();
}
}

Circle

Point

centre

xCoord
yCoord

getCentreX()
getCentreY()

getXCoord()
getYCoord()

Zahid Aslam

Objects Cleanup/Destructor

Unlike C and C++, memory deallocation is automatic in java,


dont worry about it.
no dangling pointers and no memory leak problem.
Java allows you to define a finalize method, which is invoked (if
defined) just before the object destruction.
Allows record-maintenance operations or cleaning up of any
special allocations made by the user.

// done with this circle


protected void finalize() throws IOException {
Circle.numCircles = Circle.numCircles-System.out.println(number of circles:+
Circle.num_circles);
}

Zahid Aslam

Anda mungkin juga menyukai