0% found this document useful (0 votes)
11 views

Java User-Defined Classes

The document discusses object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, and polymorphism. A class defines common attributes and behaviors for a group of objects, while objects are individual instances of a class. Constructors initialize objects when they are created.

Uploaded by

Sa F
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java User-Defined Classes

The document discusses object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, and polymorphism. A class defines common attributes and behaviors for a group of objects, while objects are individual instances of a class. Constructors initialize objects when they are created.

Uploaded by

Sa F
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Object-Oriented Design with Java

User-Defined Classes
Classes and Objects
OO Programming in Java
 Other than primitive data types (byte, short, int, long, float, double, char,
boolean), everything else in Java is of type object.
 Objects we already worked with:

String: String name = new String("John Smith");

Scanner: Scanner input = new Scanner(System.in);

1501 246 – Object Oriented Design with Java 6.3


What is an Object?
 Philosophical definition: An entity that you can recognize

 In object technology terms: An abstraction of a real-world


object
 In business terms: An entity relevant to the business
domain
 In software terms: A data structure and associated
functions

1501 246 – Object Oriented Design with Java 6.4


What is an Object?
 An object represents an entity in the real world that can be
distinctly identified. For example, student, desk, circle,
button, person, course, etc…
 An object has a unique identity, state, and behaviors.

 The state of an object consists of a set of data fields


(instance variables or properties) with their current values.
 The behavior of an object is defined by a set of methods
defined in the class from which the object is created.
 A class describes a set of similar objects.

1501 246 – Object Oriented Design with Java 6.5


Objects Perform Operations
 An object exists in order to provide behavior (function) to
the system.
 Each distinct behavior is called an operation.

Object: Operation:
my blue pen write

Object: Operation:
Acme Bank ATM withdraw

1501 246 – Object Oriented Design with Java 6.6


Objects Remember Values
 Objects have knowledge about their current state.

 Each piece of knowledge is called an attribute.

INK

Object: Attribute:
my blue pen ink amount

Object: Attribute:
Acme Bank ATM cash on hand

1501 246 – Object Oriented Design with Java 6.7


Objects Are an Abstraction
 When modeling an object, you only need to model the
operations and attributes that are important to the problem.

Real-world operation you may not want to model:


• Point with

Real-world attributes you may not want to model:


• Length
• Manufacturer
• Age

1501 246 – Object Oriented Design with Java 6.8


Encapsulation
 Encapsulation hides how things work and what they know
behind an interface—the object’s operations.
 Acme Bank ATM is an object that gives its users cash:

 The ATM encapsulates this for its users.


 Bypassing the encapsulation is bank robbery.
 Bypassing encapsulation in
object-oriented programming
is impossible.

1501 246 – Object Oriented Design with Java 6.9


What is a Class?
 A class is a template for objects.

 A class definition specifies the operations and attributes


for all instances of that class.

When you create my blue pen object, you do not have to specify its
operations or attributes. You simply say what class it belongs to.

1501 246 – Object Oriented Design with Java 6.10


Why Do We Need Classes?
 A class describes a type of object.

 A class defines the behavior and structure of a group of


objects:
 You can manage complexity by using classes.
 The world has too many objects, so people group
objects into types.
 If you understand the type, you can apply it to many
objects.

1501 246 – Object Oriented Design with Java 6.11


How Do You Identify a Class?
 Identify the common behavior and structure for a group of objects.
 Recognize a single coherent concept.

My blue pen ops: write, refill


attribs: ink amount, color of ink

Your blue pen ops: write, refill


attribs: ink amount

 Both these objects belong to the class pen.

1501 246 – Object Oriented Design with Java 6.12


Classes Versus Objects

 Classes are static definitions


 that enable us to understand all the objects of that class.
 Objects are the dynamic entities
 that exist in the real world, and our simulation of it.

 Beware—OO people almost always use the two words, classes and
objects, interchangeably;
 you need to use the context to differentiate between the two
meanings.

1501 246 – Object Oriented Design with Java 6.13


Inheritance
 There may be commonality between different classes.
 Define the common properties in a superclass.

Account

Savings account Current account

 The subclasses use inheritance to include those properties.

1501 246 – Object Oriented Design with Java 6.14


The “Is-a-Kind-of” Relationship

 A subclass object “is-a-kind-of” superclass object.


 A subclass must have all the behaviors of the superclass.

Account Pen

Savings account Pencil

1501 246 – Object Oriented Design with Java 6.15


Polymorphism

 Polymorphism means that the same operation exists in many classes.


 Each operation has the same meaning but carries out the operation in its
own unique way.

Load passengers

1501 246 – Object Oriented Design with Java 6.16


What is a Class?
 A class is the blueprint (template) that defines objects of
the same type, a set of similar object, such as students.
 The class uses methods to define the behaviors of its
objects.
 The class that contains the main method of a Java program
represents the entire program
 A class provides a special type of methods, known as
constructors, which are invoked to construct (create)
objects from the class.
 Multiple objects can be created from the same class.

1501 246 – Object Oriented Design with Java 6.17


Example

A class An object
(the concept) (the realization)

Bank Account John’s Bank Account


OwnerName Balance: $7,890
State
Balance
Deposit() Amy’s Bank Account
Behavior Withdraw() Balance: $298,987
CheckBalance()
Ed’s Bank Account
Balance: $860,883

Multiple objects
from the same class

1501 246 – Object Oriented Design with Java 6.18


Another Example

A class has both date fields (attributes/variables) and methods. The


data fields represent the state of an object; while the methods
represent the behavior of that object.

1501 246 – Object Oriented Design with Java 6.19


Constructing Objects Using
Constructors
Constructor Methods
 Constructors are special kind of methods having three
peculiarities:
1. Constructors are invoked using the new operator when an object
is created. They play the role of initializing objects.
2. The constructor method must have same name as the class
name.
3. Constructors do not have a return type, not even void.

 A constructor with no parameters is called no-arguments


constructor.
 A class can have multiple versions of the constructor
method, allowing the user to create the class object in
different ways.

1501 246 – Object Oriented Design with Java 6.21


Class Circle Constructors
class Circle {
// The radius of this circle
double radius = 1.0; Data field

// Construct a circle object


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

// Return the area of this circle


double getArea() { Method
return radius * radius * 3.14159;
// other methods
}
}
1501 246 – Object Oriented Design with Java 6.22
Creating objects of a class
 Declare the Circle class, have created a new data type – Data Abstraction
 Can define variables (objects) of that type:

Circle aCircle;
Circle bCircle;

 aCircle, bCircle simply refers to a Circle object, not an object itself.

aCircle bCircle

null null
Points to nothing (Null Reference) Points to nothing (Null Reference)

1501 246 – Object Oriented Design with Java 6.23


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();

1501 246 – Object Oriented Design with Java 6.24


Creating objects of a class

aCircle = new Circle();


bCircle = new Circle() ;

bCircle = aCircle;

Before Assignment Before Assignment

aCircle bCircle aCircle bCircle

P Q P Q

1501 246 – Object Oriented Design with Java 6.25


Summary: Creating Objects
 To reference an object, assign the object to a reference
variable.

 To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle1, myCircle2; //reference variables
myCircle1 = new Circle(); //calls first constructor
myCircle2 = new Circle(5.0); //calls second constructor

OR

Circle myCircle1 = new Circle();


Circle myCircle2 = new Circle(5.0);
1501 246 – Object Oriented Design with Java 6.26
Accessing Objects Via Reference
Variables
Accessing the Object
 An object’s data and methods can be accessed through the
dot (.) operator via the object’s reference variable.

 Referencing the object’s data:


objectRefVar.data

double myRadius = myCircle.radius; //data field

 Invoking the object’s method:


objectRefVar.methodName(arguments)

double myArea = myCircle.getArea(); //class method

1501 246 – Object Oriented Design with Java 6.28


Trace Code
Declare myCircle

Circle myCircle = new Circle(5.0); myCircle no value


Circle yourCircle = new Circle();

yourCircle.radius = 100;

1501 246 – Object Oriented Design with Java 6.29


Trace Code, cont.

Circle myCircle = new Circle(5.0);


myCircle no value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

Create a
circle

1501 246 – Object Oriented Design with Java 6.30


Trace Code, cont.

Circle myCircle = new Circle(5.0);


myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0
Assign object reference
to myCircle

1501 246 – Object Oriented Design with Java 6.31


Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

Declare
yourCircle

1501 246 – Object Oriented Design with Java 6.32


Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle no value

: Circle
Create a new radius: 1.0
Circle object

1501 246 – Object Oriented Design with Java 6.33


Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

Assign object reference


to yourCircle : Circle

radius: 1.0

1501 246 – Object Oriented Design with Java 6.34


Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();

yourCircle.radius = 100; : Circle

radius: 5.0

yourCircle reference value

: Circle
Change radius in radius: 100.0
yourCircle

1501 246 – Object Oriented Design with Java 6.35


Differences between Variables of
Primitive Data Types and Reference Types

Created using new Circle()


Primitive type int i = 1 i 1

Object type Circle c c reference c: Circle

radius = 1

1501 246 – Object Oriented Design with Java 6.36


Copying Variables of Primitive Data Types and
Reference Types
Primitive type assignment i = j

Before: After:

i 1 i 2

j 2 j 2

Object type assignment c1 = c2

Before: After:
• Shallow copying: two or
c1 c1
more reference variables of
the same type point to the c2 c2
same object
• Deep copying: each c1: Circle c2: Circle c1: Circle c2: Circle
reference variable refers to radius = 5 radius = 9 radius = 5 radius = 9
its own object

To copy an object (not its reference), you need to define a method makeCopy()
1501 246 – Object Oriented Design with Java 6.37
Garbage Collection
Example on previous slide, after the assignment statement
c1 = c2; //circle objects

c1 points to the same object referenced by c2.

The object previously referenced by c1 is no longer


referenced/accessible (i.e., garbage). Garbage is
automatically collected by JVM.

TIP: If you know that an object is no longer needed, you can


explicitly assign null to a reference variable for the object. The
JVM will automatically collect the space if the object is not
referenced by any variable in the program.

1501 246 – Object Oriented Design with Java 6.38


Encapsulation
Encapsulation
 Encapsulation is the idea of hiding the class internal details
that are not required by clients/users of the class.
 Why?
To protect data and to make classes easy to maintain and
update.
 How?
Always use private variables!

 Public variables violate encapsulation because they allow class clients to


“reach in” and modify the values directly. Therefore instance variables should
not be declared with public visibility.

1501 246 – Object Oriented Design with Java 6.40


Encapsulation
 The internal state of an object is not directly accessible to other parts of the
program
 Other parts of the program can only access the object using its interface
 We say that the state is
encapsulated or hidden getArea()
 This gives modularity
to the program . .
. .
radius
. .

getRadius()

1501 246 – Object Oriented Design with Java 6.41


Encapsulation
 The get and set methods are used to read and modify
private variables (better security).
 Data field will be updated only through setters and
retrieved by getters.
 They should be declared public

Circle
The - sign indicates
private modifier - radius: double The radius of this circle (default: 1.0).

The + sign indicates + Circle() Constructs a default circle object.


private modifier + Circle(radius: double) Constructs a circle object with the specified radius.
+ getRadius(): double Returns the radius of this circle.
+ setRadius(radius: double): void Sets a new radius for this circle.
+ getArea(): double Returns the area of this circle.

1501 246 – Object Oriented Design with Java 6.42


Encapsulation
class Circle {
// The radius of this circle
private double radius = 1.0;
Circle() { }
Circle(double newRadius) { radius = newRadius;}

public double getRadius() { return radius; }


public void setRadius(double newRadius) {
radius = (newRadius >= 0) ? newRadius : 0;
//no negative radius }

public double getArea() {


return radius * radius * 3.14159;
// other methods
}
}

1501 246 – Object Oriented Design with Java 6.43


Default Values
 The data fields can be of reference types.

 If a data field of a reference type does not reference any


object, the data field holds a special literal value null (or null
pointer) .

 For example, Class Student contains a data field name of


the type String [next slide].

1501 246 – Object Oriented Design with Java 6.44


Default Values

1501 246 – Object Oriented Design with Java 6.45


Default Values

1501 246 – Object Oriented Design with Java 6.46


Default Values Inside Methods

Rule: Java assigns no default values to local variables inside a


method. A method's local variables must be initialized.
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

1501 246 – Object Oriented Design with Java 6.47


The ‘this’ Reference
The this Keyword

 The this keyword is the name of a reference that


refers to an object itself. One common use of this
keyword is referencing a class’s hidden data fields.
 For ex: to differentiate between instance variables and
local variables

 Another common use of the this keyword to


enable a constructor to invoke another constructor of
the same class.

1501 246 – Object Oriented Design with Java 6.49


Referencing the Hidden Data Fields

public class F { Suppose that f1 and f2 are two objects of F.


private int i = 5; F f1 = new F(); F f2 = new F();
private static double k = 0;
Invoking f1.setI(10) is to execute
void setI(int i) { this.i = 10, where this refers f1
this.i = i;
} Invoking f2.setI(45) is to execute
this.i = 45, where this refers f2
static void setK(double k) {
F.k = k;
}
}

1501 246 – Object Oriented Design with Java 6.50


Calling Overloaded Constructors
public class Circle {
private double radius;

public Circle(double radius) {


this.radius = radius;
} this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
} this is used to invoke another constructor

public double getArea() {


return this.radius * this.radius * Math.PI;
}
} Every instance variable belongs to an object represented by this, which
is normally omitted

1501 246 – Object Oriented Design with Java 6.51


Note

 Java requires that the this(arg-list) statement appear first


in the constructor before any other executable statements.

 If a class has multiple constructors, it is better to implement


them using this(arg-list) as much as possible.

 In general, a constructor with no or fewer arguments can


invoke a constructor with more arguments using this(arg-
list). This syntax often simplifies coding and makes the
class easier to read and maintain.

1501 246 – Object Oriented Design with Java 6.52


Method toString()
 Example:

public String toString() {


return "Circle(radius: "+getRadius()+", area: "+getArea()+")";
}

 To return a formatted string, use String.format() method

public String toString() {


return String.format("Circle(radius: %.2f, area: %.2f)",
getRadius(), getArea());
}

1501 246 – Object Oriented Design with Java 6.54


Members Visibility
Accessibility/Visibility Modifiers
 Public : members of class are accessible outside class
 Private: members of class are not accessible outside class
 Protected: Will be covered later

 Class members can be methods or variables

 Note: class methods can (directly) access any member of


the class—data members and methods
 Therefore, when you write the definition of a method (of the
class), you can directly access any data member of the
class (without passing it as a parameter)

1501 246 – Object Oriented Design with Java 6.56


Visibility Modifiers - Comments - 1
 Class members (variables or methods) that are declared with public
visibility can be referenced/accessed anywhere in the program.

 Class members that are declared with private visibility can be


referenced/accessed only within that class.

 Class members declared without a visibility modifier have default


visibility and can be referenced/accessed by any class in the same
package.

1501 246 – Object Oriented Design with Java 6.57


Visibility Modifiers - Ex - 1

The private modifier restricts access to within a class, the default


modifier restricts access to within a package, and the public
modifier enables unrestricted access.
1501 246 – Object Oriented Design with Java 6.58
Visibility Modifiers - Ex - 2

The default modifier on a class restricts access to within a package,


and the public modifier enables unrestricted access.

1501 246 – Object Oriented Design with Java 6.59


NOTE

An object cannot access its private members, as shown in (b).


It is OK, however, if the object is declared in its own class, as
shown in (a).

1501 246 – Object Oriented Design with Java 6.60


Static Variables, Constants and
Methods
Static Variables, Constants, and Methods
Static variables are shared by all the objects of the class.
if one object changes the value of a static variable, all
objects of the same class are affected.
Static methods are not tied to a specific object, applied to
all objects of the class.
Static methods can be called without creating an instance
of the class.

1501 246 – Object Oriented Design with Java 6.62


Static Variables, Constants, and Methods
Static constants (final) are shared by all the objects
of the class.
 To declare static variables, constants, and methods,
use the static modifier.
 Note: Static variables and methods are underlined in
UML diagram
 Static methods and static data can be accessed from a
reference variable or from their class name.

1501 246 – Object Oriented Design with Java 6.63


UML

1501 246 – Object Oriented Design with Java 6.64


Example
public class Circle
{
private double radius = 1;
private static int numberOfObjects = 0;

public Circle () { numberOfObjects++; }

public Circle (double newRadius) {


radius = newRadius;
numberOfObjects++;
}

public double getRadius() { return radius; }

public void setRadius(double newRadius) {


radius = (newRadius >= 0) ? newRadius : 0;
}

public static int getNumberOfObjects(){return numberOfObjects; }

public double getArea() {return radius*radius*Math.PI; }


}

1501 246 – Object Oriented Design with Java 6.65


Example
public class TestCircle {

public static void main(String[] args) { // Main method

Circle myCircle = new Circle(10.0);


System.out.println("Number of
objects"+Circle.getNumberOfObjects());
System.out.println("The area of the circle of radius "
+ myCircle.getRadius() + " is " + myCircle.getArea());

// Increase myCircle's radius by 10%


myCircle.setRadius(myCircle.getRadius() * 1.1);

System.out.println("The area of the circle of radius "


+ myCircle.getRadius() + " is " + myCircle.getArea());

System.out.println("Number of objects
"+myCircle.getNumberOfObjects());
}
}

1501 246 – Object Oriented Design with Java 6.66


How to decide about static?

1501 246 – Object Oriented Design with Java 6.67


Immutable Objects and Classes
Immutable Objects and Classes

 If the contents of an object cannot be changed once it is created,


the object is called an immutable object and its class is called an
immutable class.

 For example, If you delete the set method in the Circle


class, the class would be immutable (not changeable) because
radius is private and cannot be changed without a set method.

 A class with all private data fields and without mutators (set
methods) is not necessarily immutable. For example, the following
class Student has all private data fields and no mutators, but it is
mutable (changeable).

1501 246 – Object Oriented Design with Java 6.69


Immutable Object Example
public class Student {
private int id; public class BirthDate {
private BirthDate birthDate; private int year;
private int month;
public Student(int ssn, private int day;
int year, int month, int day) {
id = ssn; public BirthDate(int newYear,
birthDate = new BirthDate(year, int newMonth, int newDay) {
month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId() { return id; } }

public BirthDate getBirthDate() { public void setYear(int newYear)


return birthDate; { year = newYear; }
} }
}

1501 246 – Object Oriented Design with Java 6.70


Immutable Object Example
public class Student {
private int id; public class BirthDate {
private BirthDate birthDate; private int year;
private int month;
public Student(int ssn, private int day;
int year, int month, int day) {
id = ssn; public BirthDate(int newYear,
birthDate = new BirthDate(year, int newMonth, int newDay) {
month, day); year = newYear;
} month = newMonth;
day = newDay;
public int getId() { return id; } }

public BirthDate getBirthDate() { public void setYear(int newYear)


return birthDate; { year = newYear; }
} }
}

public class Test {


public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
1501 246 – Object Oriented Design with Java 6.71
What Class is Immutable?

 Student object is dependent on and referred to a mutable


object, i.e. BirthDate. When from other BirthDate object we
set something, it will be reflected in student object.

 For a class to be immutable, it must mark all data fields


(variables) private and provide no mutator (set) methods
and no accessor (get) methods that would return a
reference to a mutable (changeable) data field object.

1501 246 – Object Oriented Design with Java 6.72


Method Overloading

Java Programming: From Problem Analysis to Program Design, 5e


Method Overloading
 Method overloading: creating several methods, within a class, with the same
name
 The signature of a method consists of the method name and its formal
parameter list
 Two methods have different signatures if they have either different names or
different formal parameter lists
Note that the signature of a method does not include the return type of the
method
 Two methods are said to have different formal parameter lists if both
methods have:
 A different number of formal parameters, or
 If the number of formal parameters is the same, then the data type of the
formal parameters, in the order you list, must differ in at least one position

1501 246 – Object Oriented Design with Java 6.74


Method Overloading

public void methodOne(int x)


public void methodTwo(int x, double y)
public void methodThree(double y, int x)
public int methodFour(char ch, int x,
double y)
public int methodFive(char ch, int x,
String name)

 These methods all have different formal parameter lists

1501 246 – Object Oriented Design with Java 6.75


Method Overloading (continued)

public void methodSix(int x, double y,


char ch)
public void methodSeven(int one, double u,
char firstCh)
 The methods methodSix and methodSeven both have three formal
parameters, and the data type of the corresponding parameters is the same
 These methods all have the same formal parameter lists

1501 246 – Object Oriented Design with Java 6.76


Method Overloading (continued)
 The following method headings correctly overload the method methodXYZ:

public void methodXYZ()


public void methodXYZ(int x, double y)
public void methodXYZ(double one, int y)
public void methodXYZ(int x, double y,
char ch)

1501 246 – Object Oriented Design with Java 6.77


Method Overloading (continued)

public void methodABC(int x, double y)


public int methodABC(int x, double y)

 Both these method headings have the same name and same formal parameter
list
 These method headings to overload the method methodABC are incorrect
 In this case, the compiler will generate a syntax error

 Notice that the return types of these method headings


are different

1501 246 – Object Oriented Design with Java 6.78


Passing Objects to Methods
Passing Objects to Methods
 Java uses exactly one mode of passing arguments: pass-by-value.
 For primitive type arguments (the value is passed to the parameter)
 For reference type arguments (the value is the reference to the object)
 In the following code, the value of myCircle is passed to the printCircle
method. This value is a reference to a Circle object.

80
1501 246 – Object Oriented Design with Java 6.80
Difference between Passing a Primitive
Value and a Reference Value

1501 246 – Object Oriented Design with Java 6.81


Difference between Passing a Primitive
Value and a Reference Value

1501 246 – Object Oriented Design with Java 6.82


Passing Objects to Methods

 When passing an argument of a reference type, the


reference of the object is passed. In this case, c contains a
reference for the object that is also referenced via
myCircle. Therefore, changing the properties of the object
through c inside the printAreas method has the same
effect as doing so outside the method through the variable
myCircle.

 Pass-by-value on references can be best described


semantically as pass-by-sharing; that is referenced in the
method is the same as the object being , the object
passed.

1501 246 – Object Oriented Design with Java 6.83


Passing Objects to Methods

1501 246 – Object Oriented Design with Java 6.84


The Scope of Variables
Scope of Variables

 We distinguish between:

 Localvariables: variables declared within a


method or block, which is visible only within that
method or block
 Instance and static variables: declared within a
class, outside of every method definition (and
every block).

1501 246 – Object Oriented Design with Java 6.86


public class F {
private int x = 0; // Instance variable
private int y = 0;

public F() {
}

public void p() {


int x = 1; // Local variable
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}

1501 246 – Object Oriented Design with Java 6.87


Scope of Local Variables

The scope of a local variable starts from its declaration point and
continues to the end of the block that contains the variable.

A local variable must be declared before it can be used.

Java Rule:
You can declare a local variable with the same name multiple times
in different non-nesting blocks in a method, but you cannot declare
a local variable twice in nested blocks.

1501 246 – Object Oriented Design with Java 6.88


Scope of Local Variables, cont.

public static void method1() {


.
.
for (int i = 1; i < 10; i++)
{
. . .
The scope of i
int j;
The scope of j . . .
}

1501 246 – Object Oriented Design with Java 6.89


Scope of Local Variables, cont.

It is fine to declare i in two It is wrong to declare i in


non-nesting blocks two nesting blocks

public static void method1() { public static void method2() {


int x = 1;
int y = 1; int i = 1;
int sum = 0;
for (int i = 1; i < 10; i++) {
x = x + i; for (int i = 1; i < 10; i++)
} sum = sum + i;
}
for (int i = 1; i < 10; i++) {
y = y + i; }
}
}

1501 246 – Object Oriented Design with Java 6.90


Scope of Local Variables, cont.

public static void illegalIdentifierDeclaration()


{
int x;

//block
{
double x; //illegal declaration,
//x is already declared
...
}
}

1501 246 – Object Oriented Design with Java 6.91


Scope of Local Variables, cont.
// Find the scoping problems in this code
public static void incorrectMethod()
{
int x = 1;
int y = 1;
for (int i = 1; i < 10; i++)
{
int x = 0;
int t = 0;
x = x + i;
}
i = i + 10;
y = y + 10;
t = t + 10;
}

1501 246 – Object Oriented Design with Java 6.92


Scope of instance variables

 The scope of instance and static variables is the entire


class. They can be declared anywhere inside a class.
 Suppose x is an identifier declared within a class and
outside of every method’s definition
 If x is declared without the reserved word static (such as
a constant or a method name), then it cannot be
accessed in a static method
 If x is declared with the reserved word static, then it can
be accessed within a method (block), provided the
method (block) does not have any other identifier named
x.

1501 246 – Object Oriented Design with Java 6.93


Scope of instance variables
public class Test {
public int x;

public static void m() {


System.out.println(x); //Cannot make a
static reference to the non-static field.
}
}

1501 246 – Object Oriented Design with Java 6.94


Scope Rules: Example
public class ScopeRules
{
static final double rate = 10.50;
static int z;
static double t;
public static void main(String[] args)
{
int num;
double x, z;
char ch;
//...
}
public static void one(int x, char y}{//...}
public static int w;
public static void two(int one, int z)
{
char ch;
int a;
//block three
{
int x = 12;
//...
} //end block three
}
} 1501 246 – Object Oriented Design with Java 6.95
Scope Rules: Demonstrated

1501 246 – Object Oriented Design with Java 6.96


Scope Rules: Demonstrated (continued)

1501 246 – Object Oriented Design with Java 6.97

You might also like