0% found this document useful (0 votes)
29 views77 pages

Objects and Classes

Uploaded by

solomondagi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views77 pages

Objects and Classes

Uploaded by

solomondagi7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Chapter 4

Objects and Classes


Outlines
 Object variables
 Defining a class
 Instantiating and using objects
 Instance fields, Construction and methods

2
Introduction
 In procedural programming, data and operations on the
data are separate.

 Object-oriented programming places data and the


operation that relate to them within a single entity called
an Object.

 The object-oriented programming approach organizes


in a way that mirrors the real world, in which all objects
are associated with both attributes and activities.
 Object-oriented programming (OOP) involves programming
using
3
objects.
Cont’d …
 Using objects improves software reusability and makes
program easier to develop and easier to maintain.

 Programming in java involves thinking in terms of


objects; a Java program can be viewed as a collection
of cooperating objects.

 An object represents an entity in the real world that can


be distinctly identified.

 For example, a student, a desk, a circle, a button, and


even a loan can all be viewed as objects.
4
Class Fundamentals

 A class is a template(model) that defines the form of an


object. It is complete definition of object.
 Specifies both the data and the code that will operate on
that data.

 Java uses a class specification to construct objects.


 N.B Class is logical abstraction & method and member
that constitute class is called member of a class.

 Although there is no syntactic rule that enforces it, a well-


designed class should define one and only one logical
entity.

5
The General Form of a Class

class classname {
// declare instance variables
type var1;
type var2;
// ...
type varN;
// declare methods
type method1(parameters) {
// body of method
}
type method2(parameters) {
// body of method
}
// ...
type methodN(parameters) {
// body of method
}
}

6
Cont…
 Although there is no syntactic rule that enforces it, a well-
designed class should define one and only one logical entity

 E.g a class that stores names and telephone numbers will


not normally also store information about the stock market,
average rainfall, or other unrelated information

 Putting unrelated information into the same class will


quickly de structure your code!

 Until now we have seen one method(main) Soon we will see


how to create others. However, notice that the general form
of a class does not specify a main( ) method.
 A main( ) method is required only if that class is the
starting
7point for your program.
Defining a Class

 To define a class you use the keyword class


followed by the name of the class, followed by
a pair of braces enclosing the details of the
definition.

class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
}

8
Cont…
 A class definition creates a new data type. In this
case, the new data type is called Vehicle.

 class declaration is only a type description; it does


not create an actual object.
 The general form of a statement that does that is
this:
ClassName variableName = new ClassName();
 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.

9
Cont…
 every Vehicle object will contain its own
copies of the instance variables passengers,
fuelcap, and mpg.
 To access these variables, you will use the dot
(.) operator.
 minivan.fuelcap = 16;

10
Progress Check

 A class contains what two things?

 What operator is used to access the


members of a class through an object?

 Each object has its own copies of the class’s


____

11
Object
 An Object can be defined as an instance of a class.
 An object has a unique identity, state, and behaviors.
 The state defines the object, and the behavior defines what the
object does.
 The state of an object consists of a set of data fields (also
known as properties) with their current values.
 The behavior of an object is defined by a set of methods.
Example: A circle object has a data field, radius, which is
the property that characterizes a circle.
 One behavior of a circle is that its area can be computed
using the method getArea().

12
Cont’d …
 If you create a software object that models television.
 The object would have variables describing the television's
current state, such as
 Its status is on,
 the current channel setting is 8,
 the current volume setting is 23, and
 The object would also have methods that describe the
permissible actions, such as
 turn the television on or off,
 change the channel,
 change the volume, and etc.

13
Class and Instances
 Objects of the same type are defined using a common class.
 In other words, a class is a blueprint, template, or prototype that
defines and describes the attributes and behaviors common to
all objects of the same kind.
 Class is objects with the same attributes and behavior .
 A class can be visualized as a three-compartment box:
 Name (or identity): identifies the class.
 Variables (or attribute, state, field): contains the attributes of the
class.
 Methods (or behaviour, function, operation): contains the dynamic
behaviours of the class.

14
Cont’d …
 The followings figure shows a few examples of classes:

15
Cont’d …
 An instance is a realization of a particular item of a class.
In other words, an instance is an instantiation of a class.
 All the instances of a class have similar properties, as
described in the class definition.
 For example, you can define a class called "Student" and
create two instances of the class "Student" for "Peter", and
"Paul“.

16
Cont’d …
 The following figure shows two instances of the class Student.

 The above class diagrams are drawn according to the UML


(Unified Modeling Language) notations.
 A class is represented as a 3-compartment box, containing
name, variables, and method.
 Class name is shown in bold and centralized. Instance name is
shown as instanceName:Classname and underlined.
17
Cont’d …

Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

. Each object within a class retains its own states and


behaviors.
18
Cont’d …
 A single class can be used to instantiate multiple objects.
This means that we can have many active objects or
instances of a class.
 A class usually represent a noun, such as a person, place or
(possibly quite abstract) thing - it is a model of concept
within a computer program.
 A Java class uses variables to define data fields and methods
to define behaviors.
 Variables and methods are called members of the class.

19
Cont’d …
 Concepts that can be represented by a class:
 Tree
 Building
 Man  Car
 Animal  Hotel
 Student  Computer Title Attributes
Author / Fields/
 Book … PubDate Properties
ISBN

setTitle(…)
setAuthor (…)
setPubDate (…)
Methods/
setISBN (…)
Behavior
getTitle (…)
getAuthor (…)

20
How Objects Are Created

Vehicle minivan = new Vehicle();


 performs two functions
 declares a variable called minivan of the
class type Vehicle and it is simply a variable
that can refer to an object………………………
 Second, the declaration creates a physical
copy of the object and assigns to minivan a
reference to that object.
 new operator dynamically allocates (that is,
allocates at run time) memory for an object
and returns a reference to it.

21
Methods

 A method contains one or more statements. In


well-written Java code, each method performs
only one task.
 you can give a method whatever name you
please
 It used to achieve reusability of code, write
once used many times
 However, don’t use Java’s keywords for
method names

22
Con’t…
 Naming method :While defining a method,
remember that the method name must be
a verb and start with a lowercase letter.

 If the method name has more than two words,


the first name must be a verb followed by
adjective or noun.

 In the multi-word method name, the first letter


of each word must be in uppercase except
the first word.
 E.g sum(), area(), areaOfCircle()
23
Con’t ….

 Types of Method: There are two types of


methods in Java:
• Predefined Method
• User-defined Method.
 In Java, predefined methods are the method that
is already defined in the Java class libraries is
known as predefined methods. It is also known as
the standard library method or built-in
method.
 Some pre-defined methods are length(),
equals(), compareTo(), sqrt(), etc
 User-defined Method: Method defined by the user

24
Constructors
 Additionally, a class provides a special type of methods,
known as constructors, which are invoked to construct new
objects from the class.
 Constructor is a special method that gets invoked
“automatically” at the time of object creation.
 A constructor can perform any action, but constructors are
designed to perform initializing actions, such as initializing the
data field of objects.
 Constructor is normally used for initializing objects with
default values unless different values are supplied.
 When objects are created, the initial value of data fields is
unknown unless its users explicitly do so.
25
Cont’d …
 In many cases, it makes sense if this initialization can be
carried out by default without the users explicitly initializing
them.
 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.
 In Java, this can be achieved through a mechanism called
constructors.
 There are two types of constructors: default and
parametrized constructors

26
Cont’d …
 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 parameter 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
parameter-less 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 Booleans).

27
Cont’d …
Differences between methods and constructors.
 Constructors must have the same name as the class itself.
 Constructors do not have a return type—not even void.
 Constructors are invoked using the new operator when an
object is created.
Defining a Constructor
public class ClassName {

// Data Fields…

// Constructor
public ClassName()
{
// Method Body Statements initialising Data Fields
}
//Methods to manipulate data fields
}
28
class MyClass {
int x;
MyClass() {
x = 10;
}
}
class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
29
Cont’d …
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */ Overloadin
Circle(double newRadius) { g
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
30
Cont’d …
 Defining a Constructor: Example
class Counter {
int CounterIndex;

// 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;
}
}

31
Cont’d …
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());
}
}

32
Cont’d …
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;
}
}
// A New User Class: Utilising both constructors
Counter counter1 = new Counter();
Counter counter2 = new Counter (10);
33
Cont’d …
 Adding a Multiple-Parameters Constructor to our Circle Class
public class Circle
{
public double x,y,r;
// Constructor
public Circle(double centreX, double centreY,double radius)

{
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;
34 }
}
Creating Objects Using Constructors
 Objects are created from classes using new operator
ClassName objectRefVar = new ClassName([parameters]);
OR
ClassName objectRefVar ;
objectRefVar = new ClassName([parameters]);
 The new operator creates an object of type ClassName.
 The variable objectRefVar references the object .
 The object may be created using any of its constructors
 If it has constructors other than the default one
appropriate parameters must be provided to create objects
using them.
35
Cont’d …
Example:
/*Declare a reference variable and create an object using an
empty constructor */
Circle c1 = new Circle();
/*Declare a reference variable and create an object using
constructor with an argument */
Circle c2 = new Circle(5.0)
//Declare reference variables
Circle c3, c4 ;
/*Create objects and refer the objects by the reference
variables
c3 = new Circle();
c4 = new Circle(8.0);

36
Accessing Objects
 Once objects have been created, its data fields can be
accessed and its methods invoked using the dot operator(.),
also known as the object member access operator.
 Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius = 100;
 Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., double area = myCircle.getArea();
 This is why it is called "object-oriented" programming; the
object is the focus.
37
Cont’d …
Circle aCircle = new Circle();
aCircle.x = 10.0; // initialize center and radius
aCircle.y = 20.0
aCircle.r = 5.0;

aCircle = new Circle();


At creation time the center and radius are not
defined. These values are explicitly set later.

Constructors initialise Objects


Circle aCircle = new Circle(10.0, 20.0,
5.0);
aCircle = new Circle(10.5,20.0, 5.0);
aCircle is created with center(10,20) and radius 5

38
Cont’d …
 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 centerX, double centerY,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; }

//Methods to return circumference and area


public double circumference() { return 2*3.14*r; }
public double area() { return 3.14 * r * r; }
} 39
Cont’d …
 Initializing with constructors
public class TestCircles {

public static void main(String args[]){


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

Circle circleC = new Circle();


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

Centre = (10,12) Centre = (0,0) Centre = (0,0)


Radius = 20 Radius=10 Radius = 1
40
Exercise
 Define a employee class
 Define Different Constructors
 Create objects per your constructors
 Access object properties and methods of your class
 Show method & constructor overloading
 Different ways to create an object in java

41
Variables of Primitive Data Types Vs. Object Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c=new Circle() c reference c: Circle

radius = 1

Object type assignment c1 = c2


Primitive type assignment i = j Before: After:
Before: After:
c1 c1

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

42
Garbage Collection
 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.
 That is the JVM will automatically collect the space if
the object is not referenced by any variable.
 As shown in the previous figure, after the assignment
statement c1 = c2, c1 points to the same object referenced
by c2.
 The object previously referenced by c1 is no longer referenced.
 This object is known as garbage.
 Garbage is automatically collected by JVM.

43
Classes Declaration
 Class declaration has the following syntax
[ClassModifiers] class ClassName [pedigree]
{
//Class body;
}
 Class Body may contain
 Data fields:

[FieldModifier(s)] returnType varName ;


 Constructors:
[Modifiers] ClassName(…){…}
 Member Methods:
[MethodModifier(s)] returnType methodName(…){…}

And even other classes



 Pedigree - extends, implements( …will see it later)
44
Data fields
 Data Fields are variables declared directly inside a class (not
inside method or constructor of a class)
 Data fields can be variables of primitive types or reference
types. public class Student {
 Example String name;
int age;
boolean isSci;
char gender;
}

 The default value of a data field is null for a reference type, 0 for
a numeric type, false for a boolean type, and '\u0000' for a char
type.
 Data fields can be initialized during their declaration.
 However, the most common way to initialize data fields is inside
constructors.
45
Cont’d …
 Java assigns no default value to a local variable inside a
method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}

Compilation error: variables not initialized

46
Types of Variables
Local variable: Created inside a method or block of statement
E.g. public int getSum(int a, int b)
{
int sum=0;
sum=a+b; This method has local variables such as a, b, sum.
return sum; Their scope is limited to the method.
}

Instance variable: Created inside a class but outside any method. Store
different data for different objects.
E.g.
public class Sample1 {
int year; This method has two instance variables year and month.
int month;
public void setYear(int y)
O1 Instanc
{ year=y;} e
… variabl
e
} Each object has its own data for the instance variable O2 Instanc
e
47 variabl
e
Cont’d …
Static variable: Created inside a class but outside any method. Store
one data for all objects/instances.
E.g. public class Sample {
static int year; This class has one static variable: year
int month;
public static void setYear(int y) {
year=y;}
Shared by
… } all objects/
instances
• Static/class variables store O1 O4
values for the variables in
common memory location. O5
• Because of this common O2 Static
location, all objects of the variable
same class are affected if one O6
object changes the value of a O stands for
Object
static variable. O3
48
Cont’d …
 We define class variables by including the static keyword
before the variable itself.
Example: class FamilyMember {
static String surname = "Johnson";
String name;
int age;
... }
 Instances of the class FamilyMember each have their own
values for name and age.
 But the class variable surname has only one value for all family
members.
 Change surname, and all the instances of FamilyMember are
affected.

49
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:
int LargerOne = Math.max(x, y);

50
Cont’d …
 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)
 General use for java static methods is to access static fields.

51
Cont’d …
 Constants in class are shared by all objects of the class.
Thus, constants should be declared final static.

Example: The constant PI in the Math class is defined as:

final static double PI = 3.14159265


 Static variables and methods can be used from instance or
static method in the class.
 Instance variables and methods can only be used from
instance methods, not from static methods.
 Static variables and methods belong to the class as a whole
and not to particular objects.
52
Cont’d …
Example:
public class Foo{
int i=5;
Static int k = 2;
public static void main(String[] args)
{ int j = i; // wrong i is instance variable
m1(); //wrong m1() is an instance method
}
public void m1()
{
//Correct since instance and static variables and can be used in an instance method.
i = i + k + m2(int i,int j);
}
public static int m2(int I, int j)
{ return (int)(Math.pow(i,j)); }
}53
Con’t…
 A method that has static keyword is known as
static method.
 Example: main Method
 Method of a class known as Instance Method-
non static method defined in the class.

54
Modifiers in Java
 Java provides a number of access modifiers to help you set the
level of access you want for classes as well as the fields,
methods and constructors in your classes.
 Access modifiers are keywords that help set the visibility and
accessibility of a class, its member variables, and methods.
 Determine whether a field or method in a class, can be used or
invoked by another method in another class or subclass.
Could one class Class Name2
Class Name1 directly access
Attribute area another class’s Attribute area
methods or
attributes?
Method area Method area

Encapsulation
55
Cont’d …
 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.
 The two levels are class level access modifiers and member
level access modifiers.

56
Cont’d …
1. Class level access modifiers (java classes only)
 Only two access modifiers is allowed, public and no modifier
 If a class is ‘public’, then it CAN be accessed from
ANYWHERE.
 If a class has ‘no modifer’, then it CAN ONLY be accessed
from ’same package’.

2. Member level access modifiers (variables and


methods)
 All the four public, private, protected and no modifer is
allowed.

57
Cont’d …
public access modifier
 The class, data, or method is visible to any class in any package.
 Fields, methods and constructors declared public (least
restrictive) within a public class are visible to any class in the
Java program, whether these classes are in the same package or
in another package.
private access modifier
 The private (most restrictive) fields or methods can be
accessed only by the declaring class.
 Fields, methods or constructors declared private are strictly
controlled, which means they cannot be accesses by anywhere
outside the enclosing class.
 A standard design strategy is to make all fields private and
provide public getter and setter methods for them to read and
modify.
58
Cont’d …
protected access modifier
 The protected fields or methods cannot be used for classes in
different package.
 Fields, methods and constructors declared protected in a
superclass can be accessed only by subclasses in other
packages.
 Classes in the same package can also access protected
fields, methods and constructors as well, even if they are not
a subclass of the protected member’s class.
No modifier (default access modifier)
 Java provides a default specifier which is used when no
access modifier is present.
 Any class, field, method or constructor that has no declared
access modifier is accessible only by classes in the same
package.
59
Cont’d …
 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

60
Cont’d …
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

61
Cont’d …
class Accessible only in its package
None
(package) interface Accessible only in its package
member Accessible only in its package

class Make an inner class top-level class.

method A class method, invoked through the class


name.
static field A class field, invoked through the class
name one instance, regardless of class
instances created.
initializer Run when the class is loaded, rather than
when an instance is created.
private member Accessible only in its class(which defines it).

62
Cont’d …
class Accessible anywhere

public interface Accessible anywhere

member Accessible anywhere its class is.

protected member Accessible only within its package and its


subclasses
class All methods in the class are implicitly
strictfp.

method All floating-point computation done is


strictfp strictly conforms to the IEEE 754 standard.
All values including intermediate results
must be expressed as IEEE float or double
values. It is rarely used.
63
Cont’d …
method For a static method, a lock for the class is
synchronized acquired before executing the method.
For a non-static method, a lock for the
specific object instance is acquired.

transient field Not be serialized with the object, used with


object serializations.

volatile field Accessible by unsynchronized threads, very


rarely used.

•The table(matrix) in the next slide shows java modifiers indicating


summary of which modifier to which element can be applied.

64
Cont’d …

65
Cont’d …
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();
} } }
} } }

package p1; package p2;


class C1 { public class C2 { public class C3 {
... can access C1 cannot access C1;
} } can access C2;
}
66
This Keyword
 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.

67
Con’t ….
 There are a lot of usage of java this keyword
some of them:
 Refer current class instance variable
 Invoke current class method
 Invoke current class constructor
 Pass argument in method call
 Pass argument in constructor call

68
Cont’d …
 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.
public class Point
{
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b)
{ x = a;
y = b; }
}
69
Cont’d …
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor public
Point(int x, int y)
{ this.x = x;
this.y = y;
} As we can see in the program that we have
} declare the name of instance variable and local
variables same. Now to avoid the confliction
70 between them we use this keyword.
Example
Class
Name

Data Filelds

Constructors

Initializing attributes

71
Cont’d …
 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.
 Use this to invoke an overloaded constructor of the same class.
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;
72 this.height = height; } }
Cont’d …
 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.

73
Cont’d …

74
Getters and Setters Method
 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 in
Java.
75
Cont’d …
public class Circle {
private double x,y,r;
public double getX() { return x;}
public double getY() { return y;}
public double getR() { return r;}
public void setX(double x_in) { x = x_in;}
public void serY(double y_in) { y = y_in;}
public void setR(double r_in) { r = r_in;}
//Methods to return circumference and area
}
 Better way of initialising or access data members x, y, r
 To initialise/Update a value: aCircle.setX( 10 )
 To access a value: aCircle.getX()
 These methods are informally called as Accessors or Setters/Getters
Methods.

76
77
?

You might also like