Chapter 2. (Class Object)
Chapter 2. (Class Object)
2
programming using objects.
Introduction
7
Class
8
Class and Instances
The followings figure shows a few examples of classes:
9
Class and Instances
An instance is a realization of a particular item of a class.
In other words, an instance is an instantiation of a class.
Data Fields:
radius is _______
Methods:
getArea
setTitle(…)
setAuthor (…)
Methods/ setPubDate (…)
Behavior setISBN (…)
getTitle (…)
14 getAuthor (…)
…
Class…
A Java class uses variables to define data fields and
methods to define behaviors.
For example,
If you create an object of the class called “Counter”, it is
natural to assume that the counter record-keeping field is
initialized to zero unless otherwise specified differently.
17
Constructors
Constructors has exactly the same name as the defining
class.
Like regular methods, constructor can be overloaded.(i.e. A
class can have more than one constructor as long as they have
different signature (different input arguments syntax).
This makes it easy to construct objects with different initial data
values.
Default constructor
If you don't define a constructor for a class, a default parameterless
constructor is automatically created by the compiler.
The default constructor calls the default parent constructor
(super()) and initializes all instance variables to default value (zero
for numeric types, null for object references, and false for
18
Booleans).(Inheritance…will see it later )
Constructors…
19
Constructors…
Defining a Constructor
Like any other method
public class ClassName {
// Data Fields…
// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
20
Classes, Example
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field
// Constructor
public Counter()
{
CounterIndex = 0;
}
//Methods to update or access counter
public void increase()
{
CounterIndex = CounterIndex + 1;
}
public void decrease()
{
CounterIndex = CounterIndex - 1;
}
int getCounterIndex()
{
return CounterIndex;
}
}
22
Constructors…
class MyClass {
public static void main(String args[])
{
Counter counter1 = new Counter();
counter1.increase();
int a = counter1.getCounterIndex();
counter1.increase();
int b = counter1.getCounterIndex();
if ( a > b )
counter1.increase();
else
counter1.decrease();
System.out.println(counter1.getCounterIndex());
}
}
23
Constructors…
A Counter with User Supplied Initial Value ?
This can be done by adding another constructor method to
the class.
public class Counter {
int CounterIndex;
// Constructor 1
public Counter()
{
CounterIndex = 0;
}
public Counter(int InitValue )
{
CounterIndex = InitValue;
}
}
{
x = centreX;
y = centreY;
r = radius;
}
//Methods to return circumference and area
public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
}
25
Creating Objects Using Constructors
objectRefVar.methodName(arguments)
e.g., double area = myCircle.getArea();
This is why it is called "object-oriented" programming; the
object is the focus.
28
Constructors…
29
Constructors…
Constructors initialise Objects
With defined constructor
30
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.
public class Circle {
public double x,y,r; //instance variables
// Constructors
public Circle(double centreX, double cenreY, double
radius)
{
x = centreX; y = centreY; r = radius;
}
public Circle(double radius) { x=0; y=0; r = radius; }
public Circle() { x=0; y=0; r=1.0; }
radius = 1
i 1 i 2
c2 c2
i 2 j 2
c1: Circle C2: Circle c1: Circle C2: Circle
radius = 5 radius = 9 radius = 5 radius = 9
33
Garbage Collection
• The object becomes a candidate for automatic garbage
collection.
39
Types of Variables
Instance variable
Created inside a class but outside any method. Store
different data for different objects.
E.g.
40 .
Types of Variables
Static variable
Created inside a class but outside any method. Store
one data for all objects/instamces.
E.g.
public class Sample {
static int year;
int month;
public static void setYear(int y) {
year=y;
}
… This class has
} one static
variable: year
41
Types of Variables
Shared by all
objects/instanc
O1 es O4
O2
O5
Static variable
O3 O6
O stands for Object
42
Instance vs. Static variables
O1 Instance O4
Instance variable
variable
Each object
has its own
data for the
instance Instance
variable variable
O2 Instance
variable O5
Instance
Instance variable
variable
O3 O6
O stands for Object
43
Member Methods
A method declared inside the class definition is a
member methed
46
Static/class Variables…
If we want all the instances of a class to share data, use
static variables.
Static/class variables store values for the variables in
common memory location. Because of this common
location, all objects of the same class are affected if
one object changes the value of a static variable.
With instance variables, each new instance of the
class gets a new copy of the instance variables that
class defines.
47
Static/class Variables…
48
Static/class Variables…
We define class variables by including the static keyword
before the variable itself.
Example:
class FamilyMember {
static String surname = "Johnson";
String name;
int age;
...
}
50
Static/Class Methods
Class methods, like class variables, apply to the
class as a whole and not to its instances.
Class methods are commonly used for general utility
methods that may not operate directly on an instance
of that class, but fit with that class conceptually.
For example, the class method Math.max() takes
two arguments and returns the larger of the two. You
don't need to create a new instance of Math; just call
the method anywhere you need it, like this:
51
int LargerOne = Math.max(x, y);
Static/Class Methods
Good practice in java is that, static methods should be
invoked with using the class name though it can be
invoked using an object.
ClassName.methodName(arguments)
OR
objectName.methodName(arguments)
52
Notes
Constants in class are shared by all objects of the
class. Thus, constants should be declared final static.
Method area
?
Encapsulation
Method area
56
Modifiers in Java
Access Modifiers
private
protected
no modifier (also sometimes referred as ‘package-
private’ or ‘default’ or ‘friendly’ access. )
public
Modifiers are applied by prefixing the appropriate
keyword for the modifier to the declaration of the
class, variable, method or constructor.
Combinations of modifiers may be used in
meaningful ways.
57
Modifiers in Java
The two levels are class level access modifiers
and member level access modifiers.
59
Modifiers in Java
public access modifier
60
Modifiers in Java
private access modifier
The private (most restrictive) fields or methods can be
accessed only by the declaring class.
63
Modifiers in Java
For better understanding, member level access is
formulated as a table:
Same Other
Access Same Class Subclass
Package packages
Modifiers
public Y Y Y Y
protected Y Y Y N
no access
Y Y N N
modifier
private Y N N N
64
Modifiers in Java
First row {public Y Y Y Y} should be interpreted as:
65
Modifiers in Java…
Modifier Used on Meaning
class Contains unimplemented methods and cannot
be instantiated.
Abstract interface All interfaces are abstract. Optional in
declarations
method No body, only signature. The enclosing class
is abstract
class Cannot be subclassed
method Cannot be overridden and dynamically
looked up
Final
field Cannot change its value. static final fields are
compile-time constants.
variable Cannot change its value.
native method Platform-dependent. No body, only signature
66
Modifiers in Java…
class Accessible only in its package
None
(package) interface Accessible only in its package
member Accessible only in its package
70
package p1; package p2;
public class C1 { public class C2 { public class C3 {
public int x; void aMethod() { void aMethod() {
int y; C1 o = new C1(); C1 o = new C1();
private int z; can access o.x; can access o.x;
can access o.y; cannot access o.y;
public void m1() { cannot access o.z; cannot access o.z;
}
void m2() { can invoke o.m1(); can invoke o.m1();
} can invoke o.m2(); cannot invoke o.m2();
private void m3() { cannot invoke o.m3(); cannot invoke o.m3();
} } }
} } }
71
This keyword
a) Within an instance method or a constructor, this is a
reference to the current object (the object whose
method or constructor is being called)
Use this to refer to the object that invokes the
instance method.
72
This keyword
b) The most common reason for using the this keyword is
because a field is shadowed by a method or constructor
parameter. (to avoid name conflicts.)
Use this to refer to an instance data field.
For example, the Point class was written like this
Data Filelds
Constructors
Initializing attributes
75
This keyword
c) From within a constructor, you can also use the this keyword
to call another constructor in the same class. Doing so is
called an explicit constructor invocation.
76
This keyword
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle(){
this(0, 0, 0, 0);
}
public Rectangle(int width, int height){
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int
height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
77 }
This keyword
For Example:
The no-argument constructor calls the four-argument
constructor with four 0 values.
The two-argument constructor calls the four-
argument constructor with two 0 values.
As before, the compiler determines which
constructor to call, based on the number and the type
of arguments.
If present, the invocation of another constructor
must be the first line in the constructor.
78
This keyword…
79
Getters and Setters Methods
A class’s private fields can be manipulated only by
methods of that class.
So a client of an object—that is, any class that calls the
object’s methods—calls the class’s public methods to
manipulate the private fields of an object of the class.
Classes often provide public methods to allow clients of
the class to set (i.e., assign values to) or get (i.e., obtain
the values of) private instance variables.
The names of these methods need not begin with set or
get, but this naming convention is highly recommended
80 in Java
Getters and Setters Methods
–
public class Circle {
private double x,y,r;
81
Getters and Setters Methods
Better way of initialising or access data members x,
y, r