INTRODUCTION
• The classis at the core of Java. It is the logical construct upon which
the entire Java language is built because it defines the shape and nature
of an object.
• As such, the class forms the basis for object-oriented programming in
Java. Any concept you wish to implement in a Java program must be
encapsulated within a class.
• Class Fundamentals : Perhaps the most important thing to understand about a
class is that it defines a new data type.
• In Java main() is encapsulated by class.
• Once defined, this new type can be used to create objects of that type.
• Thus, a class is a template for an object, and an object is an instance of a class.
4.
The General Formof a Class
• When you define a class, you declare its exact form and nature. You do this by specifying the
data that it contains and the code that operates on that data. While very simple classes may
contain only code or only data, most real-world classes contain both.
• A class is declared by use of the class keyword. The classes that have been used up to this
point are actually very limited examples of its complete form.
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Contd….
• 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.
• Thus, as a general rule, it is the methods that determine how a class’ data can be used.
• 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.
Thus, the data for one object is separate and unique from the data for another.
• All methods have the same general form as main( ), which we have been using thus
far. However, most methods will not be specified as static or public.
• Notice that the general form of a class does not specify a main( ) method. Java
classes do not need to have a main( ) method. You only specify one if that class is
the starting point for your program.
A Simple Class
•Let’s begin our study of the class with a simple example. Here is a class called Box
that defines three instance variables: width, height, and depth.
class Box
{
double width;
double height;
double depth;
}
9.
Contd…
• 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. It is important to remember
that a class declaration only creates a template; it does not create an actual object.
• Thus, the preceding code does not cause any objects of type Box to come into
existence.
• To actually create a Box object, you will use a statement like the following:
Box mybox = new Box( ); // create a Box object called mybox
• After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality.
• As mentioned earlier, 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.
• To access these variables, you will use the dot (.) operator.
• The dot operator links the name of the object with the name of an instance variable.
10.
Contd…
• For example,to assign the width variable of mybox the value 100, you would use
the following statement:
mybox.width = 100;
• This statement tells the compiler to assign the copy of width that is contained
within the mybox object the value of 100.
• In general, you use the dot operator to access both the instance variables and the
methods within an object.
11.
/* A programthat uses the Box class. Call this file
BoxDemo.java*/
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String[] args)
{
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
12.
Contd…
• To runthis program, you must execute BoxDemo.class. When you do, you will see
the following output:
Volume is 3000.0
• As stated earlier, each object has its own copies of the instance variables. This means
that if you have two Box objects, each has its own copy of depth, width, and
height.
• It is important to understand that changes to the instance variables of one object have
no effect on the instance variables of another.
• As you can see, mybox1’s data is completely separate from the data
contained in mybox2
14.
Declaring Objects
• Asjust explained, when you create a class, you are creating a new data type. You can
use this type to declare objects of that type.
• However, obtaining objects of a class is a two-step process.
- First, you must declare a variable of the class type. This variable does not define
an object. Instead, it is simply a variable that can refer to an object.
-- Second, you must acquire an actual, physical copy of the object and assign it to
that variable.
• You can do this using the new operator.
• The new operator dynamically allocates (that is, allocates at run time) memory
for an object and returns a reference to it.
• This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
• In the preceding sample programs, a line similar to the following is used to declare an
object of type Box:
• This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:
• Box mybox; // declare reference to object Box mybox = new Box( );
mybox = new Box(); // allocate a Box object
15.
Contd….
• The firstline declares mybox as a reference to an object of type Box.
• After this line executes, mybox contains the value null, which indicates that it
does not yet point to an actual object.
• Any attempt to use mybox at this point will result in a compile-time error.
• The next line allocates an actual object and assigns a reference to it to mybox.
• After the second line executes, you can use mybox as if it were a Box object.
• But in reality, mybox simply holds the memory address of the actual Box object.
A Closer Look at new
• As just explained, the new operator dynamically allocates memory for an object.
It has this
general form:
class-var = new classname( );
16.
Contd….
Here, class-var isa variable of the class type being created. The classname is the
name of the class that is being instantiated.
The class name followed by parentheses specifies the constructor for the class.
A constructor defines what occurs when an object of a class is created. Constructor
are an important part of all classes and have many significant attributes.
17.
Contd…
• Most real-worldclasses explicitly define their own constructors within their class
definition.
• However, if no explicit constructor is specified, then Java will automatically supply a
default constructor.
• This is the case with Box. For now, we will use the default constructor.
• you might be wondering why you do not need to use new for such things as integers
or characters.
• The answer is that Java’s primitive types are not implemented as objects. Rather, they
are implemented as “normal” variables.
• Objects have many features and attributes that require Java to treat them differently
than it treats the primitive types.
• By not applying the same overhead to the primitive types that applies to objects, Java
can implement the primitive types more efficiently.
• It is important to understand that new allocates memory for an object during run
time.
• The advantage of this approach is that your program can create as many or as few
objects as it needs during the execution of your program.
18.
Contd…
• However, sincememory is finite, it is possible that new will not be able to allocate
memory for an object because insufficient memory exists. If this happens, a run-
time exception will occur.
• Let’s once again review the distinction between a class and an object. A class creates
a new data type that can be used to create objects.
• That is, a class creates a logical framework that defines the relationship between its
members. When you declare an object of a class, you are creating an instance of that
class.
• Thus, a class is a logical construct. An object has physical reality. (That is, an object
occupies space in memory.) It is important to keep this distinction clearly in mind.
19.
Assigning Object ReferenceVariables
• Object reference variables act differently than you might expect when an assignment takes
place.
Box b1 = new Box();
Box b2 = b1;
• You might think that b2 is being assigned a reference to a copy of the object referred to by
b1.
• That is, you might think that b1 and b2 refer to separate and distinct objects. However, this
would be wrong.
• Instead, after this fragment executes, b1 and b2 will both refer to the same object.
• The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object.
• It simply makes b2 refer to the same object as does b1. Thus, any changes made to the
object through b2 will affect the object to which b1 is referring, since they are the same
object.
b1 b2
20.
Contd….
• Although b1and b2 both refer to the same object, they are not linked in any
other way.
• For example, a subsequent assignment to b1 will simply unhook b1 from the
original object without affecting the object or affecting b2.
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
• Here, b1 has been set to null, but b2 still points to the original object.
21.
Introducing Methods
• Asmentioned 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.
• 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 name(parameter-list)
{
// body of method
}
• 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 name. This can be any legal identifier other
than those already used by other items within the current scope.
22.
Contd….
• The parameter-listis 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.
• Methods that have a return type other than void return a value to the calling routine
using the following form of the return statement:
return value;
• Here, value is the value returned.
• Adding a Method to the Box Class : Although it is perfectly fine to create a
class that contains only data, it rarely happens. Most of the time, you will use
methods to access the instance variables defined by the class.
• In fact, methods define the interface to most classes.
• This allows the class implementor to hide the specific layout of internal data
structures behind cleaner method abstractions.
• In addition to defining methods that provide access to data, you can also define
methods that are used internally by the class itself.
• Let’s begin by adding a method to the Box class.
23.
Contd…
• It mayhave 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 class
rather than the BoxDemo class.
• 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.
• CONSIDER the FOLLOWING EXAMPLE
• Look closely at the following two lines of code:
mybox1.volume();
mybox2.volume();
The first line here invokes the volume( ) method on mybox1. that is, it calls
volume( ) relative to the mybox1 object, using the object’s name followed by the
dot operator.
Thus, the call to mybox1.volume( ) displays the volume of the box defined by
mybox1.
• The call to mybox2.volume( ) displays the volume of the box defined by mybox2.
Each time volume( ) is invoked, it displays the volume for the specified box.
25.
Contd…
• When mybox1.volume() is executed, the Java run-time system transfers control
to the code defined inside volume( ).
• After the statements inside volume( ) have executed, control is returned to the calling
routine, and execution resumes with the line of code following the call.
• There is something very important to notice inside the volume( ) method: the
instance variables width, height, and depth are referred to directly, without
preceding them with an object name or the dot operator.
• When a method uses an instance variable that is defined by its class, it does so
directly, without explicit reference to an object and without use of the dot operator.
• A method can directly invoke all the instance variable of the class if the method is
present in the same class.
• This means that width, height, and depth inside volume( ) implicitly refer to the
copies of those variables found in the object that invokes volume( ).
• When an instance variable is accessed by code that is not part of the class in which
that instance variable is defined?
• It must be done through an object, by use of the dot operator.
• However, when an instance variable is accessed by code that is part of the same class
as the instance variable, that variable can be referred to directly.
26.
Returning a Value
•While the implementation of volume( ) does move the computation of a box’s
volume inside the Box class where it belongs, it is not the best way to do it.
• A better way to implement volume( ) is to have it compute the volume of the box
and return the result to the caller.
CONSIDER THE EXAMPLE
• As you can see, when volume( ) is called, it is put on the right side of an
assignment statement. On the left is a variable, in this case vol, that will receive the
value returned by volume( ). Thus, after
vol = mybox1.volume();
executes, the value of mybox1.volume( ) is 3,000 and this value then is stored in vol.
• There are two important things to understand about returning values:
1) The type of data returned by a method must be compatible with the return type
specified by the method. For example, if the return type of some method is boolean,
you could not return an integer.
2) The variable receiving the value returned by a method (such as vol, in this case)
must also be compatible with the return type specified for the method.
27.
Adding a MethodThat Takes Parameters
• While some methods don’t need parameters, most do. 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.
• Method Without Parameter Method With Parameter
int square( )
{
return 10 * 10;
}
int square(int i)
{
return i * i;
}
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.
Now, square( ) will return the square of whatever value it is called with. That is,
square( ) isnow a general-purpose method that can compute the square of any integer
value, rather than just 10.
28.
Contd…
• Here isan example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
• 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.
• You can use a parameterized method to improve the Box class. In the preceding
examples, the dimensions of each box had to be set separately by use of a sequence
of statements, such as:
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
Argument
29.
// This programuses a parameterized method.
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth; }
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main(String[] args) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
Output:
Volume is 3000.0
Volume is 162.0
When this programis run, it generates the following
results:
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
32.
Parameterized Constructors
• Whilethe Box( ) constructor in the preceding example does initialize a Box
object, it is not very useful—all boxes have the same dimensions.
• What is needed is a way to construct Box objects of various dimensions. The easy
solution is to add parameters to the constructor.
• EXAMPLE
The this Keyword: Sometimes a method will need to refer to
the object that invoked it. To allow this, Java defines the this
keyword.
this can be used inside any method to refer to the current
object. That is, this is always a reference to the object on which
the method was invoked.
You can use this anywhere a reference to an object of the
current class’ type is permitted.
36.
class Thisdemo
{
int a=100;
voiddisplay()
{
int a=200;
System.out.println(a);
System.out.println(this.a);
}
public static void main(String[] args)
{
Thisdemo obj1=new Thisdemo();
obj1.display();
}
}
class Thisdemo
{
int a=100;
void display()
{
int a=200;
System.out.println(a);
}
public static void main(String[] args)
{
Thisdemo obj1=new Thisdemo();
obj1.display();
}
}
37.
Instance Variable Hiding
•It is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes.
• Interestingly, you can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables.
• However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
• This is why width, height, and depth were not used as the names of the parameters
to the Box( ) constructor inside the Box class.
• If they had been, then width would have referred to the formal parameter, hiding the
instance variable width.
• While it is usually easier to simply use different names, there is another way around
this situation.
• Because this lets you refer directly to the object, you can use it to resolve any name
space collisions that might occur between instance variables and local variables.
38.
EXAMPLE
• For example,here is another version of Box( ), which uses width, height, and depth
for parameter names and then uses this to access the instance variables by the
same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
• A word of caution: The use of this in such a context can sometimes be confusing,
and some programmers are careful not to use local variables and formal parameter
names that hide instance variables.
• that it is a good convention to use the same names for clarity, and use this to
overcome the instance variable hiding.
39.
Garbage Collection
• Sinceobjects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
• In some languages, such as C++, dynamically allocated objects must be manually
released by use of a delete operator.
• Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
• It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed. There is
no explicit need to destroy objects as in C++.
• Garbage collection only occurs sporadically (if at all) during the execution of your
program. It will not occur simply because one or more objects exist that are no longer
used.
40.
A Closer Lookat Methods and Classes
• Overloading Methods : In Java it is possible to define two or more methods
within the same class that share the same name, as long as their parameter
declarations are different.
• When this is the case, the methods are said to be overloaded, and the process is
referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
• Thus, overloaded methods must differ in the type and/or number of their parameters.
• While overloaded methods may have different return types, the return type alone is
insufficient to distinguish two versions of a method.
• When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call
EXAMPLE.
41.
class OverloadDemo {
voidtest() {
System.out.println("No parameters");
}
void test(int a) {
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String[] args) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
42.
This program generatesthe following
output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
43.
// Automatic typeconversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String[] args) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
44.
This program generatesthe following output:
No parameters
a and b: 10 20
Inside test(double) a: 88.0
Inside test(double) a: 123.2
45.
Overloading Constructors
• Inaddition to overloading normal methods, you can also overload constructor
methods. In fact, for most real-world classes that you create, overloaded constructors
will be the norm, not the exception.
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
As you can see, the Box( )
constructor requires three
parameters. This means that all
declarations of Box objects must
pass three arguments to the
Box( ) constructor.
Box ob = new Box( );
// This is invalid here
46.
Contd…
•It leads tosome important questions…
• Can we find out initial dimensions of Box..
• What will the value when no dimension is specified for Box.
• Can we find volume of Cube.. Etc…
• To all the above questions we have solution : simply overload the Box constructor so
that it handles the situations just described.
EXAMPLE
class OverloadCons {
publicstatic void main(String[] args) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
49.
Using Objects asParameters
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[ ]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
output:
ob1 == ob2: true
ob1 == ob3: false
Output:
Volume of mybox1is 3000.0
Volume of mybox2 is -1.0
Volume of cube is 343.0
Volume of clone is 3000.0
class OverloadCons2 {
public static void main(String[] args) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Box myclone = new Box(mybox1); // create copy of mybox1
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}
52.
Argument Passing
Note thatthe values remain unchanged, demonstrating that primitive
types are passed by value, and modifications to the parameters within
the method do not affect the original variables outside the method.
// Primitive types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String[] args) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
53.
The output fromthis program is shown here:
a and b before call: 15 20
a and b after call: 15 20
54.
// Objects arepassed through their references.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class PassObjRef {
public static void main(String[] args) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +
ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +
ob.a + " " + ob.b);
}}
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
55.
Returning Objects
A methodcan return any type of data, including
class types that you create.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}}
class RetOb {
public static void main(String[] args) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: "+ ob2.a);
}}
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second
increase: 22
56.
Recursion Java supportsrecursion. Recursion is the process of
defining something in terms of itself. A method that calls
itself is said to be recursive.
// A simple example of recursion.
class Factorial {
int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String[] args)
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
57.
// Another examplethat uses recursion.
class RecTest {
int[] values;
RecTest(int i) {
values = new int[i];
}
// display array -- recursively
void printArray(int i) {
if (i == 0)
return;
else
printArray(i - 1);
System.out.println("[" + (i - 1) + "] " + values[i - 1]);
}
}
class Recursion2 {
public static void main(String[] args) {
RecTest ob = new RecTest(10);
int i;
for (i = 0; i < 10; i++)
ob.values[i] = i;
ob.printArray(10);
}
}
58.
This program generatesthe following
output:
[9] 9
[8] 8
[7] 7
[6] 6
[5] 5
[4] 4
[3] 3
[2] 2
[1] 1
[0] 0
59.
Introducing Access Control
Java’saccess modifiers are public, private, and protected. Java also
defines a default access level. protected applies only when inheritance
is involved.
60.
/* This programdemonstrates the difference between public and
private.*/
class Test {
int a; // default access
public int b; // public access
private int c; // private access
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c; }}
class AccessTest {
public static void main(String[] args) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " +
ob.getc());
}}
61.
Understanding static
When amember is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.
You can declare both methods and variables to be static. The most
common example of a static member is main( ). main( ) is declared
as static because it must be called before any objects exist. Instance
variables declared as static are, essentially, global variables. When
objects of its class are declared, no copy of a static variable is made.
Instead, all instances of the class share the same static variable.
Methods declared as static have several restrictions:
• They can only directly call other static methods of their class.
• They can only directly access static variables of their class.
• They cannot refer to this or super in any way.
62.
// Demonstrate staticvariables, methods, and blocks.
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String[] args) {
meth(42);
}
}
63.
Here is theoutput of the program:
Static block initialized.
x = 42
a = 3
b = 12
64.
Outside of theclass in which they are defined, static methods and variables can be
used independently of any object. Here is an example. Inside main( ), the static
method callme( ) and the static variable b are accessed through their class name
StaticDemo.
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String[] args)
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Introducing final
A fieldcan be declared as final. Doing so prevents its contents from
being modified, making it, essentially, a constant. This means that you
must initialize a final field when it is declared.
You can do this in one of two ways: First, you can give it a value when it
is declared. Second, you can assign it a value within a constructor.
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;
In addition to fields, both method parameters and local variables can
be declared final.
• Declaring a parameter final prevents it from being changed within
the method.
• Declaring a local variable final prevents it from being assigned a
value more than once.
67.
class Bike9{
final intspeedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Compile by: javac Bike9.java
154.136/Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
68.
Introducing Nested andInner
Classes
• It is possible to define a class within another class; such classes are
known as nested classes.
• The scope of a nested class is bounded by the scope of its enclosing
class. Thus, if class B is defined within class A, then B does not exist
independently of A.
There are two types of nested classes: static and non-static.
1. A static nested class is one that has the static modifier applied.
Because it is static, it must access the non-static members of its
enclosing class through an object. That is, it cannot refer to non-
static members of its enclosing class directly.
2. The second type of nested class is the inner class. An inner class is
a non-static nested class. It has access to all of the variables and
methods of its outer class and may refer to them directly in the
same way that other non-static members of the outer class do.
69.
class Outer
{
int outer_x= 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
class Inner
{
void display()
{
System.out.println("display: outer_x = " +
outer_x);
}}
}
class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.test();
}}
Output:
display: outer_x = 100
70.
// Define aninner class within a for loop.
class Outer {
int outer_x = 100;
void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}
class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.test();
}
}
71.
The output fromthis version of the program is shown here:
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100