Definition
Class
Is a software design that describes the common attribute
and activities of objects.
-- attributes represent the properties of the object
-- activities represent the actions exhibited by the object
It is a collection of objects of similar type.
Cont..
Classes are user-defined data types & behave like the
built-in types of programming language
Class defines the state and behavior of the basic
programming components known as objects.
A class defines the skeleton of an object.
Illustration
Cont..
Object
Object is an instance (member) of a class.
Objects have
-- State (values held by attributes)
-- Identity (through w/c they can be uniquely identified)
-- Behavior (actions done by the object)
Created by using new operator.
An Object's behavior is defined by its methods.
Cont..
States [1001,Alice, 1002, Joana……]
Identity [customer ID]
Behavior (method) [purchase]
General form of Class
A class is declared by the use of the class keyword.
class classname {//class start
type methodname2(parameter-list) {
type instance-variable1;
// body of method
type instance-variable2;
}
// ...
// ...
type instance-variableN;
type methodnameN(parameter-list) {
type methodname1(parameter-list){
// body of method
// body of method
}
}
}//class end
Cont..
The data, or variables, defined within a class are called
instance variables. The code is contained within methods.
Collectively, the methods and variables defined within a class
are called members of the class.
In most classes, the instance variables are acted upon and
accessed by the methods defined for that class.
Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the
class) contains its own copy of these variables.
Cont..
class Box {
double width;
double height;
double depth;
}
As stated, a class defines a new type of data.
In this case, the new data type is called Box.
You will use this name to declare objects of type Box.
Creating Objects
An object in Java is essentially a block of memory that contains space to store all
the instance variables.
Creating an object also known as instantiating an object.
Objects in Java are created using the new operator.
The new operator creates an object of the specified class and returns a reference
to that object.
Syntax for object creation:
classname objectname; //declaration
objectname = new classname( ); // instantiation
Cont..
Cont..
Box bx = new Box(); // create a Box object called bx
After this statement executes, bx will be an instance of Box.
Thus, it will have “physical” reality.
Again, each time you create an instance of a class, you are creating
an object that contains its own copy of each instance variable
defined by the class.
Thus, every Box object will contain its own copies of the instance
variables width, height, and depth.
Accessing instance variables
To access instance variables of a class, you will use the
dot (.) operator.
The dot operator links the name of the object with the
name of an instance variable.
For example, to assign the width variable of bx the value
100, you would use the following statement:
[Link] = 100;
Sample code
class Box {
double width;
double height;
double depth;
public static void main(String args[]) {
Box bx = new Box();
double vol;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link]("Volume is " + vol);
}
} Output: Volume is 3000
Cont..
It is important to understand that change to the instance variables
of one object has no effect on the instance variables of another.
class Box { [Link] = 3;
double width;
double height; [Link] = 6;
double depth; [Link] = 9;
public static void main(String args[]) vol = [Link] * [Link] * [Link];
{ [Link]("Volume is " + vol);
Box bx1 = new Box();
Box bx2 = new Box(); vol = [Link] * [Link] * [Link];
double vol; [Link]("Volume is " + vol);
[Link] = 10;
}}
[Link] = 20;
The output produced by this program is
[Link] = 15;
shown here:
Volume is 3000.0
Volume is 162.0
Assigning object reference variables
When you assign one object reference variable to another
object reference variable, you are not creating a copy of the
object, you are only making a copy of the reference.
Box b1 = new Box();
Box b2 = b1;
It simply makes b2 refer to the same object as does b1.
Cont..
// Assume we have student class and 1022 is memory address
students stud1= new students(“Teborne”, “2233/02”);
students stud2;
Memory address will be given at the time of
object instantiation using new keyword
stud1 1022
stud2 ?
Somewhere in the memory
1022 Teborne 2233/02
Cont..
// Assume we have student class and 1022 is memory address
students stud1= new students(“Teborne”, “2233/02”);
students stud2=stud1; //stud2 points to the memory address that is pointed by stud1
stud1 1022
stud2
Somewhere in the memory
1022 Teborne 2233/02
Cont..
Although b1 and b2 both refer to the same object, they are not
linked in any other way.
For example, a subsequent assignment to b1 will simply undo b1
from the original object without affecting the object or affecting b2.
For example:
Box b1 = new Box();
Box b3 = new Box();
Box b2 = b1;
// ...
b1 = b3;
Here, b1 points the object pointed by b3, but b2 still points to the
previous object.
Cont..
// Assume we have student class and 1022/1023 are memory address
students stud1= new students(“Teborne”, “2233/02”);
students stud3= new students(“Sucre”, “2337/07”);
students stud2=stud1;
stud1=stud3; // points the same memory address
1022
stud1 1023
stud2
Teborne 2233/02
stud3 1022
1023 Sucre 2337/07
Change on stud1 after assignment has no effect on stud2
Sample code
Introducing Methods (Functions)
As mentioned at the beginning of this chapter, classes usually consist of two
things: instance variables and methods.
The topic of methods is a large one because Java gives them so much power and
flexibility.
However, there are some fundamentals that you need to learn now so that you can
begin to add methods to your classes. This is the general form of a method:
type methodname (parameter-list) {
// body of method
}
Cont..
Here, type specifies the type of data returned by the method.
This can be any valid type, including class types that you create.
If the method does not return a value, its return type must be void.
The name of the method is specified by methodname.
Parameter-list is a sequence of type and identifier pairs separated by
commas.
Parameters are essentially variables that receive the value of the arguments
passed to the method when it is called.
If the method has no parameters, then the parameter list will be empty.
Adding a Method to a Class
Let’s begin by adding a method to the Box class.
It may have occurred to you while looking at the preceding
programs that the computation of a box’s volume was something
that was best handled by the Box .
After all, since the volume of a box is dependent upon the size of
the box, it makes sense to have the Box class compute it.
To do this, you must add a method to Box, as shown here:
Sample code
class Box { [Link] = 3;
double width; [Link] = 6;
double height; [Link] = 9;
double depth;
void volume() { [Link]();
[Link]("Volume is "); [Link]();
[Link](width * height * depth); }
} }
public static void main(String args[]) { This program generates the following
Box bx1 = new Box(); output
Box bx2 = new Box(); Volume is 3000.0
[Link] = 10; Volume is 162.0
[Link] = 20;
[Link] = 15;
Adding a Method that takes parameters
Parameters allow a method to be generalized.
That is, a parameterized method can operate on a variety of data
and/or be used in a number of slightly different situations.
To illustrate this point, let’s use a very simple example.
Here is a method that returns the square of the number 10:
int square()
{
return 10 * 10;
}
Cont..
While this method does, indeed, return the value of 10 squared, its
use is very limited.
However, if you modify the method so that it takes a parameter, as
shown next, then you can make square( ) much more useful.
int square(int i)
{
return i * i;
}
Now, square( ) will return the square of whatever value it is called
with.
That is, square( ) is now a general-purpose method that can
compute the square of any integer value, rather than just 10.
Cont..
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
In the first call to square( ), the value 5 will be passed into parameter i.
In the second call, i will receive the value 9.
The third invocation passes the value of y, which is 2 in this example.
As these examples show, square( ) is able to return the square of whatever
data it is passed.
Cont..
It is important to keep the two terms parameter and argument
straight.
A parameter is a variable defined by a method that receives a value
when the method is called.
For example, in square ( ), i is a parameter.
An argument is a value that is passed to a method when it is
invoked.
For example: square (100) passes 100 as an argument.
Inside square( ), the parameter i receives that value.
You can use a parameterized method to improve the Box class.
Set instance variables values by method
In the preceding examples, the dimensions of each box had to be set
separately by use of a sequence of statements, such as:
[Link] = 10;
[Link] = 20;
[Link] = 15;
While this code works, it is troubling for two reasons.
First, it is clumsy and error prone. For example, it would be easy to
forget to set a dimension.
Second, in well-designed Java programs, instance variables should
be accessed only through methods defined by their class.
Cont..
Thus, a better approach to setting the dimensions of a box is to create a
method that takes the dimension of a box in its parameters and sets
each instance variable appropriately.
class Box { public static void main(String args[]) {
double width; Box bx1 = new Box();
double height; Box bx2 = new Box();
double depth; double vol;
// compute and return volume [Link](10, 20, 15);
double volume() { [Link](3, 6, 9);
return width * height * depth; vol = [Link]();
} [Link]("Volume is " + vol);
void setDim(double w, double h, vol = [Link]();
double d) { [Link]("Volume is " + vol);
width = w; }
height = h; }
depth = d;
}
Cont..
As you can see, the setDim( ) method is used to set the
dimensions of each box.
For example, when [Link](10, 20, 15); is executed, 10 is
copied into parameter w, 20 is copied into h, and 15 is
copied into d.
Inside setDim( ) the values of w, h, and d are then assigned
to width, height, and depth, respectively.
Constructor
It can be tedious to initialize all of the variables in a class each time an instance is
created. Even when you add convenience functions like setDim()
It is possible to initialize objects they are created by:
>> Using the dot operator
>> The help of methods
But it would be simpler and more concise to initialize an object when it is first
created.
Java supports a special type of method, called a constructor, that enables an
object to initialize itself when it is created.
Constructors are special methods that are used to construct an instance of a class.
A constructor initializes an object immediately upon creation.
Call the constructor(s) preceding it with the new keyword.
Rules with constructor
Class name and constructor name should be the same. That is, it has
the same name as the class in which it resides and is syntactically
similar to a method.
Constructors have no return type (not even void), this is because
they return the instance of the class itself.
Constructors should be public.
Constructors can not be inherited.
They can be overloaded. Many constructors with the same name can
be defined.
Constructor and normal method
Constructor Normal method
Has no return type Has return type
Its name should the same as class name Its name can be any identifier
Invoked with new keyword. Can be invoked without new keyword.
Types of constructor
1. Default constructor
is a constructor which receives no arguments.
has no parameters
Default parameters defined automatically (if there is no parameterized
constructor)
Default parameters defined by the programmer.
2. Parameterized Constructor:
is a constructor w/c can receives one or more arguments.
has one or more parameters
o When an instance of an object is created then the instance will call the constructor.
o It will be called based on the types of constructor that has been called while object is
created.
Default constructor sample code
class
{
() //default constructor
Output
{
=====
[Link](“Hello”);
Hello
}
public static void main(String args[])
{
Employee emp = new employee();
}
}
Parameterized constructor sample code
class
{
String Ename;
float salary;
(String name, float sal) //parameterized constructor
{
Output
Ename= name; =====
salary = sal;
Teborne 4500.00
[Link](Ename +”\t”+ salary);
}
public static void main(String args[])
{
Employee emp = new employee(“Teborne”,4500.00);
}}
Overloaded constructor
Constructor with the same name, but the compiler uses two mechanism to differentiate
the overloaded constructors.
number of parameter
data type of parameter
public class students{ public static void main(String[] args){
String name;
students() students stud1=new students();
{
[Link](“default constructor”); students stud2=new students(“Teborne”);
}
students(String name) Output
}
{ ======
}
[Link]=name; default constructor
[Link]([Link]); Teborne
}
“This” keyword
this implicit reference to current object.
used to:
-- prevent instance variables hiding by local variable.
-- improve readability of the program
-- invoke the constructor.
class students{ “this” keyword
String name; allow us to use the same identifier for
students(String name) instance variable and local variable
{ to prevent instance variables hiding
[Link]=name; by local variable
}
}
Using objects as parameter
public class Boxx { public static void main(String[] args){
double wid,het,dep; Boxx b=new Boxx();
Boxx() Using object as [Link]=10;
parameter
{} [Link]=20;
Boxx(Boxx bx) [Link]=15;
{ Boxx bb=new Boxx(b);
wid=[Link]; }
het=[Link]; }
dep=[Link]; Output
======
3000
[Link](wid*het*dep);
}
Returning objects
public class Rectangle { public static void main(String[] args)
{
int len,wid; Rectangle r=new Rectangle(40, 50);
Rectangle(int l, int w) Rectangle r2;
{ r2=[Link]();
len=l; [Link]([Link]+" "+[Link]);
wid=w; [Link]([Link]+" "+[Link]);
} }
Rectangle getRectangle() }
Output
{
======
Rectangle rect=new Rectangle(10,20); 40 50
10 20
return rect; //returning object
}
Passing arguments
There are two ways that a computer language can pass an argument to a subroutine.(passing
by value and passing by reference).
Passing by- value -This method copies the value of an argument into the formal parameter
of the subroutine.
Therefore, changes made to the parameter variable values have no effect on the
argument variable values.
Used to pass simple data types.(primitive data type)
Passing by reference -In this method, a reference to an argument (not the value of the
argument) is passed to the parameter.
changes made to the parameter variable values will affect the argument variable
values.
Used to pass objects.
Passing arguments: sample codes
// pass by value public class ByRference {
public class ByValue { int a,b;
Output
void Test(int j,int i) ByRference(int j,int i) { ======
a=j; 15 20
{ Output 30 10
i*=2; ====== b=i;
j/=2; 15 20 }
15 20
} void Test(ByRference ref) {
public static void main(String[] args) { ref.a=ref.a*2;
ByValue bx=new ByValue(); ref.b=ref.b/2;
int a=15; }
int b=20; public static void main(String[] args) {
[Link](a+" "+b); ByRference reff=new ByRference(15,20);
[Link](a,b); [Link](reff.a+" "+reff.b);
[Link](a+" "+b); [Link](reff);
} [Link](reff.a+" "+reff.b);
} }}