4.
Creating Class and Object
1
Classes
A Java class member may have:
- instance variables to define data fields/attributes
and
- instance methods to define behaviors.
Additionally, a class provides a special type of
methods, known as constructors, which are invoked
to construct objects from the class.
2
UML Class Diagram for Employee
Class name
Employee
- empnum: int Attributes / instance variables that
- empname: String define the object’s state; can hold
numbers, characters, strings, other
+ setEmpNum(int): void objects
+ getEmpNum(): int
+ setEmpName(String): void
+ getEmpName(): String Actions that an object of this
class can take (behaviors)
3
The Employee Class Shell
4
Data Fields
Variables declared within class
But outside of any method
Called instance variables (local)
When not static (global)
Each class will have own copy of each
non-static data field
private access for fields
No other classes can access field’s values
Only methods of same class allowed to use
private variables
5
You name it!
Data Fields (cont’d)
private [static] [final] datatype name;
Usually
private primitive: int, double,
etc., or an object:
May be present: String, Image, Foot
means the field is
shared by all May be present:
objects in the class means the field
is a constant
private int empnum;
6
Creating Instance Methods in a Class
Classes contain methods
Non-static method
Instance methods
“Belong” to objects
Typically declare non-static instance
variables
static class variables
Are not instance variables
7
7
Method Definitions
Method header form:
modifier returnType methodName ([parameterList])
Example:
public double getPrice()
public void setPrice(double aPrice)
Method names usually sound like verbs.
The name of a method that returns the value of a
field often starts with get:
getWidth, getX
The name of a method that sets the value of a
field often starts with set:
setLocation, setText
8
Understanding Data Hiding
Data hiding using encapsulation
Data fields usually private
Client application accesses them only through
public interfaces
Set method
Controls data values used to set variable
Get method
Controls how value retrieved
9
Accessor and Mutator Methods
The methods that retrieve the data of
fields are called accessors.
The methods that modify the data of
fields are called mutators.
10
Accessors and Mutators
For the rectangle example, the accessors and
mutators are:
getLength: Returns the value of the length field.
public double getLength() { }
getWidth : Returns the value of the width field.
public double getWidth() { }
setLength : Sets the value of the length field.
public void setLength(double len) { }
setWidth : Sets the value of the width field.
public void setLength(double w) { }
11
Class Definition
public class Employee {
private int empnum;
private String empname;
Employee
public void setEmpNum(int num) {
- empnum: int empnum = num;
- empname: String }
+ setEmpNum(int): void public int getEmpNum() {
+ getEmpNum(): int return empnum;
+ setEmpName(String): void }
+ getEmpName(): String
public void setEmpName(Strig name) {
UML class diagram empname = name;
}
public String getEmpName() {
return empname;
}
} 12
Declaring Objects or Create an Instance
Declaring class does not create any
actual objects – only the template
Create instance of class
Supply type and identifier
Allocate computer memory for object
13
Declaring Object Reference Variable
and Create Object
To refer an object, assign the object to a
reference variable.
To declare a reference variable, use the syntax:
ClassName objectRefVar;
To create object:
objectRefVar = new ClassName();
Example:
Employee emp1;
emp1 = new Employee();
14
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference Create an object
Example:
Employee emp1 = new Employee();
15
Accessing Objects
After object instantiated, methods accessed using:
Object’s identifier
Dot
Data/Method call
Referencing the object’s data:
objectRefVar.data
Example:
emp1.empnum
Invoking the object’s method:
objectRefVar.methodName(arguments)
Example:
emp1.getEmpNum()
16
Constructors
Special kind of methods for creating objects of the
class.
A class may be declared without constructors.
If a programmer does not define any constructors,
Java will automatically provides one default no-args
constructor, which allocates memory and sets fields
to the default values
Name of constructor always same as name of class.
Default constructors do not have a return type (not
even void) and they do not return a value.
Example: public Employee() { }
17
Class Definition with default constructor
public class Employee {
private int empnum;
private String empname;
Employee public Employee() {
- empnum: int System.out.println (“Start Employee”);
}
- empname: String
+ Employee() public void setEmpNum(int num) {
+ setEmpNum(int): void empnum = num;
+ getEmpNum(): int }
public int getEmpNum() {
+ setEmpName(String): void
return empnum;
+ getEmpName(): String
}
public void setEmpName(String name) {
empname = name;
UML class diagram
}
public String getEmpName() {
return empname;
} 18
}
Constructors
Constructors may take parameters.
If
a constructor has one parameter, we
may call it as one-argument constructor.
If a class has more than one
constructor, they must have different
numbers and/or types of parameters.
This is called constructor overloading
19
Creating Object == invoking Constructors
Constructors are invoked using the new
operator when an object is created.
Constructors play the role of initializing
objects.
Format:
new ClassName();
Example:
new Employee();
new Employee(123, “Ahmad”);
20
Constructors (cont’d)
public class Fraction public Fraction (int n, int d)
{ {
private int num, denom; num = n;
denom = d;
public Fraction ( ) reduce ();
{ }
num = 0;
denom = 1; “No-args” public Fraction (Fraction other)
} constructor {
num = other.num;
public Fraction (int n) denom = other.denom;
{ }
num = n; ... Copy
denom = 1;
} Continued }
constructor
21
Constructors (cont’d)
A nasty bug:
public class MyWindow
extends JFrame
{
...
// Constructor: Compiles fine, but
public void MyWindow ( ) the compiler thinks
{ this is a method and
...
}
uses MyWindow’s
... default no-args
constructor instead.
22
Constructors (cont’d)
Constructors of a class can call each other using
the keyword this — a good way to avoid
duplicating code:
public class Fraction ...
{ public Fraction (int p, int q)
... {
num = p;
public Fraction (int n) denom = q;
{ reduce ();
this (n, 1); }
} ...
...
23
Organizing Classes
Place data fields in logical order
At beginning of class
Fields listed vertically
May place data fields and methods in any
order within a class
Common to list all data fields first
Can see names and data types before reading
methods that use data fields
24
Employee.java
import ... import statements
public class Employee Class header
{ Attributes / variables that define the
Fields object’s state; can hold numbers,
characters, strings, other objects
Procedures for constructing
Constructors
a new object of this class
and initializing its fields
Methods Actions that an object
of this class can take
} (behaviors) 25
public class Circle {
private double radius, area;
final PI = 3.14159; File Name?
Save as “______.java”
Circle (double r) {
radius = r;
}
public double findArea() {
area= radius*radius*PI;
return area;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle circle1 = new Circle(2.3);
System.out.println("The area of the circle of radius "+ circle1.radius + " is " +
circle1.findArea());
}
}
26