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

Java Module2ISE

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

Java Module2ISE

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

MODULE 2 CLASSES and METHODS

MODULE 2

Introducing Classes:
 Class Fundamentals
 Declaring Objects
 Assigning Object Reference Variables
CLASSES  Introducing Methods
 Constructors
 The this Keyword
METHODS  Garbage Collection.
Methods and Classes:
 Overloading Methods
 Objects as Parameters
 Argument Passing
 Returning Objects
 Recursion
 Access Control
 Understanding static
 Introducing final
 Introducing Nested and Inner Classes.

DEPT OF ISE,SJCIT 2023 Page 1


MODULE 2 CLASSES and METHODS

Chapter -1
Introducing Classes

Class Fundamentals:
Qp) Write a note on
a. defining class in java
b. object instantiation

a. Defining class in JAVA


 class is a Keyword .
 class is a collection of fields, methods, constructors, and certain properties.
 class acts like a blueprint.
 When defining class , it should starts with keyword class followed by name of the class; and
the class body, enclosed by a pair of curly braces.
Syntax:
Public class class_name
{
type instance-variable1;
type instance-variable2;
type instance-variableN; //variables(fields or members)

type methodname1(parameter-list)//method(member function)


{
// body of method
}

 The data, or variables, defined within a class are called instance variables.
Collectively, the methods and variables defined within a class are called members of
the class.
 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.
 Note: 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. Further, applets don’t require a main( ) method at all.

DEPT OF ISE,SJCIT 2023 Page 2


MODULE 2 CLASSES and METHODS

Example:
package mypack;
public class box
{
double width;
double height;//creates only a template
double depth;//no actual data
}

class boxdemo1
{
public static void main(String[] args)
{
box mybox=new box();//create a box object called mybox
double vol;
mybox.width=10;
mybox.height=10;
mybox. depth=15;
vol=mybox.width*mybox.height*mybox. depth;
System.out.println("volume is "+vol);
}

 Class defines a new type of data.


 In the above example ,mybox will be an instance of box. Thus every box object will contain
its own copies of the instance variables width, height and depth.
 Dot (.) operator is used to access the variables. The dot operator links the name of the object
with the name of the instance variable.
Ex: mybox.width=100;

DEPT OF ISE,SJCIT 2023 Page 3


MODULE 2 CLASSES and METHODS

//program declares two box objects.

package mypack;
public class box
{
double width;
double height;//creates only a template
double depth;//no actual data
}

class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();//create a box object called mybox1
box mybox2=new box();// 2nd object called mybox2

double vol;
mybox1.width=10; Output:
mybox1.height=20; Volume is 3000.0
mybox1. depth=15; Volume is 162.0

mybox2.width=3;
mybox2.height=6;
mybox2. depth=9;

vol=mybox1.width*mybox1.height*mybox1.depth; //volume of first box


System.out.println("volume is "+vol);

vol=mybox2.width*mybox2.height*mybox2.depth; //volume of first box


System.out.println("volume is "+vol);

Declaring object:
b. Object Instantiation
 Object is a instance of the class.
 Object is used to access members and member functions.
 When you create a class, you are creating a new data type. You can use this type to
declare objects of that type.
 Object is created using new keyword , which allocates the memory for object when its
created.
 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.

DEPT OF ISE,SJCIT 2023 Page 4


MODULE 2 CLASSES and METHODS

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.


 To declare an object of type Box:

Box mybox = new Box();

 This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:

Step1: Box mybox; // declare reference to object

mybox NULL

 The first line 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.

Step 2: mybox = new Box(); // allocate a Box object

mybox width
height
depth
Box object

 The above line allocates an actual object and assigns a reference to it to mybox. After
the second line executes, you can use mybox as a Box object.
 But in reality, mybox simply holds the memory address of the actual Box object.
Assigning object Reference Variables:
 A reference variable is used to access the object of a class. Reference variables are created at the
program compilation time.
 Reference variable is just a alias name for object.
 Object reference variables act differently than you might expect when an assignment takes place.

DEPT OF ISE,SJCIT 2023 Page 5


MODULE 2 CLASSES and METHODS

width
Height
For example, b1
Box b1=new Box( ) ; Depth
Box b2=b1 ; b2

Box object

 We might think that b2 is being assigned a reference to a copy of the object referred to by
b1. That is, we might think that b1and b2 refer to separate and distinct objects.
 However, this would be wrong. Instead, after this fragment executes, b1and 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 b1is
referring, since they are the same object.
 Example:b1=null;
 b1 will simply unhook b1 from the original object without affecting the object b2.
 b1 has been set to null, but b2 still points to the original object.

Introducing Methods:
 We already know that class contains members (instance variables) and member functions
(methods).
This is the general form of a method:
<Access modifier><Return type><Method name>(parameter List)
{

// Method body

Following are the elements of a method –

Access modifier: this determines the visibility of a variable or a method from another class.
Return type: A method may return a value. If a method is not returning any value then method return
data type should be void, if method returning integer value then method return type should be int, etc.,
Method name: It’s a unique identifier and it’s case sensitive. It cannot be same as any other identifier.

DEPT OF ISE,SJCIT 2023 Page 6


MODULE 2 CLASSES and METHODS

Parameter List: enclosed between parenthesis. Parameter List is optional that is, a method may contain
no parameters.
Method Body: this contains the set of instructions need to complete the required activity.
Scope
 Local Scope:
o The variables which are declared inside one method, we cannot use the same
variables in other method.
o The left and right curly braces that form the body of a method create scope.
 Class Scope:
o The variable which are declared inside the class and outside all the methods,
which are used in any methods known as Class Scope.

We can write method in different ways depends on return value –


 Writing method –
o Without parameters and without return value.
o Without parameters and with a return value.
o With parameters and without return value.
o With parameters and with return value.
Without parameters and without return value:
 In this type A Method will not accept any parameters and not return any value to the Main
method.

public class box


{
double width;
double height;
double depth;
//display volume of a box
Void volume()// Method Without parameters without return value.
{
System.out.println(“volume is “);
System.out.println(width*height*depth);
}
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();
mybox1.width=10;
mybox1.height=20;
mybox1. depth=15;
mybox1.volume();
}
}

DEPT OF ISE,SJCIT 2023 Page 7


MODULE 2 CLASSES and METHODS

Without parameters and with a return value:(Returning a value)


 In this type A Method will not accept any parameters and return value to the Main method.
//Now, volume() returns the volume of a box
public class box
{
double width;
double height;
double depth;
//display volume of a box
double volume()// Method Without parameters with return value.
{
Return width*height*depth;
}
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();
double vol;
mybox1.width=10;
mybox1.height=20;
mybox1. depth=15;
vol=mybox1.volume();
System.out.println("volume is "+vol);
}
}
There are two important things to understand about the 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 same method is boolean, you could not return an interger.
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.

With parameters and without return value:


 In this type A Method will accept parameters but not return value to the Main method.

package mypack;

public class box


{
Public void volume(double weight,double height,double depth)
{
double vol;
vol=weight*height*depth;
System.out.println("volume is: " +vol );
}
public static void main(String[] args)
{
box mybox1 = new box( ) ;
mybox1.volume(20,30,10) ;
}
}

DEPT OF ISE,SJCIT 2023 Page 8


MODULE 2 CLASSES and METHODS

With parameters and with return value:


 In this type A Method will accept parameters and return value to the Main method.

package mypack;

public class box


{

public double volume(double weight,double height,double depth)


{
double vol;
vol=weight*height*depth;
return vol;
}
public static void main(String[] args)
{
box mybox1 = new box( ) ;
double vol =mybox1.volume(20,30 ,10) ;
System.out.println("volume is: " +vol );
}
}

Qp)What is Constructor? How it differs from other member functions? Explain


different types of constructors in java with examples.

 Definition: it is method which is having same name as that of the class in which it is
defined.
 A constructor initializes an object immediately upon creation. It has the same name as
the class in which it resides and is syntactically similar to a method.
 Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
 Constructors look a little strange because they have no return type, not even void.
 This is because the implicit return type of a class’ constructor is the class type itself.
 It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.
 Every time an object is created using the new( ) keyword, at least one constructor is
called.
 It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
Two types of constructors are
a. Default constructor
b. Parameterized constructor

DEPT OF ISE,SJCIT 2023 Page 9


MODULE 2 CLASSES and METHODS

a) Default constructor:
 If a constructor method doesn’t have any parameters then we call it as parameter less
constructor or default constructor.
 These methods can be defined by the programmer explicitly, or else will be defined
implicitly provided by the compiler.
 In Implicit constructors, the default value for integer is 0, for boolean is false, for string is null.,
etc.
class Box
{
double width;
double height;
double depth;
OUTPUT:
Box()
{ Volume is 1000.0
width = 10; Volume is 1000.0
height = 10;
depth = 10;
}

double volume()
{
return width * height * depth;
}
}

class BoxDemo {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

DEPT OF ISE,SJCIT 2023 Page 10


MODULE 2 CLASSES and METHODS

b) Parameterized Constructors
 If a Constructor method is defined with parameters, we call that as parameterized
constructor.
 Parameterized constructor should be defined by the programmer but never defined by the compiler
implicitly.
class Box
{
double width;
double height;
double depth;

Box(double w, double h, double d)


{
width = w; height = h; depth = d;
}

double volume( ) OUTPUT:


{ Volume is 3000
return width * height * depth; Volume is 162
}
}

class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

this keyword:
 In Java, this is a reference variable that refers to the current object.
 Uses –
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this( ) can be used to invoke current class constructor. Etc..,

The this keyword can be used to refer current class instance variable. If there is ambiguity
(confusion) between the instance variables and local parameters, this keyword resolves the problem
of ambiguity.

Box(double width, double height, double depth)


{

DEPT OF ISE,SJCIT 2023 Page 11


MODULE 2 CLASSES and METHODS

this.width = width;
this.height = height;
this.depth = depth;
}

Qp)Write a note on
c. instance variable hiding(use of this keyword)
d. static and static block
e. garbage collection
f. finalization(finalize())

a. Instance Variable Hiding(use of this keyword)


 It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes.
 We 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.
 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;
}

 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.

DEPT OF ISE,SJCIT 2023 Page 12


MODULE 2 CLASSES and METHODS

b. static and static block


 Normally a class member must be accessed only in conjunction with an object of its
class. However, it is possible to create a member that can be used by itself, without
reference to a specific instance.
 To create such a member, precede its declaration with the keyword static. When a
member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object.
 Class members will be used independently without any references using Static keyword.
 You can declare both methods and variables to be static. 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:
i. They can only call other static methods.
ii. They must only access static data.
iii. They cannot refer to this or super in any way
 Example:
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);
}

S
ttatic
{
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String args[])


{
meth(42);
}
}

DEPT OF ISE,SJCIT 2023 Page 13


MODULE 2 CLASSES and METHODS

output :
Static block initialized.
x = 42
a=3
b = 12
 If you wish to call a static method from outside its class, you can do so using the
following general form:
classname.method( )

Here, classname is the name of the class in which the static method is declared
Example:
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();//no object is needed for static
System.out.println("b = " + StaticDemo.b);
}
}

output
a = 42
b = 99

c. Garbage Collection
 Since objects 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
DEPT OF ISE,SJCIT 2023 Page 14
MODULE 2 CLASSES and METHODS

released by use of a delete operator. Java takes a different approach; it handles ideal
location 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.
Furthermore, different Java run-time implementations will take varying approaches to
garbage collection.

d. The finalize( ) Method


 Sometimes an object will need to perform some action when it is destroyed. For
example, if an object is holding some non-Java resource such as a file handle or
character font, then you might want to make sure these resources are freed before an
object is destroyed. To handle such situations, Java provides a mechanism called
finalization.
 By using finalization, you can define specific actions that will occur when an object is
just about to be reclaimed by the garbage collector.
 To add a finalizer to a class, you simply define the finalize( ) method. The Java run
time calls that method whenever it is about to recycle an object of that class.
 Inside the finalize( ) method, you will specify those actions that must be performed
before an object is destroyed.
 The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.
 Right before an asset is freed, the Java run time calls the finalize( ) method on the
object.

 The finalize( ) method has this general form:

protected void finalize( )


{
// finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
 It is important to understand that finalize( ) is only called just prior to garbage
collection. It is not called when an object goes out-of-scope, for example. This means

DEPT OF ISE,SJCIT 2023 Page 15


MODULE 2 CLASSES and METHODS

that you cannot know when—or even if—finalize( ) will be executed.


 Therefore, your program should provide other means of releasing system resources,
etc., used by the object. It must not rely on finalize( ) for normal program operation.

Qp)Write a JAVA program to implement the stack operations that holds 10 elements?

// This class defines an integer stack that can hold 10 values.


class Stack
{
int stck[] = new int[10];
int top;

// Initialize top-of-stack
Stack()
{
top= -1;
}

// Push an item onto the stack


void push(int item)
{
if(top==9)
System.out.println("Stack is full.");
else
stck[++top] = item;
}

// Pop an item from the stack


int pop()
{
if(top < 0)
{
System.out.println("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}

DEPT OF ISE,SJCIT 2023 Page 16


MODULE 2 CLASSES and METHODS

Class StackDemo
{
Public static void main(String args[])
{
Stack ob=new stack(10);
for(int i=0;i<10;i++)
ob.push(i);
System.out println(“elements of stack are”);
for(int i=0;i<10;i++)
ob.pop();
}
}

As you can see, the Stack class defines two data items and three methods. The stack
of integers is held by the array stck. This array is indexed by the variable top, which always
contains the index of the top of the stack.
The Stack( ) constructor initializes top to –1, which indicates an empty stack. The
method push( ) puts an item on the stack. To retrieve an item, call pop( ). Since access to the
stack is through push( ) and pop( ), the fact that the stack is held in an array is actually not
relevant to using the stack.

output:
Stack elements are:
9
8
7
6
5
4
3
2
1
0

DEPT OF ISE,SJCIT 2023 Page 17


MODULE 2 CLASSES and METHODS

Chapter -2
Methods and classes
Method overloading:
 Java allows us to create more than one method with same name, but with different
parameter list and different definitions. This is called method overloading.
 Method overloading is used when methods are required to perform similar tasks but using
different input parameters. Overloaded methods must differ in number and/or type of
parameters they take. This enables the compiler to decide which one of the definitions to
execute depending on the type and number of arguments in the method call.
Example:
public class First
{
public void Addition( int a, int b)
{
System.out.println(a+b);
}
public void Addition( int a, int b,int c) Output:
{ 30
System.out.println(a+b+c); 60
}
public static void main(String[] args){
First obj = new First( ) ;
obj.Addition(10, 20);
obj.Addition(10, 20, 30);
}}

Objects and methods (Using Objects as Parameters to methods):So far, we have only been using simple
types as parameters to methods. However, it is bothcorrect and common to pass objects to methods
public class test

int a,b;
test(int i,int j)//parameterized constructor

a=i;b=j;

boolean equals(test o)//passing object as parameter

if(o.a==a && o.b==b) Output:


return true; ob1==ob2 true
ob1==ob3 false
else
return false;

public class passob


public static void main(String[] args)
test ob1=new test(10,20);
test ob2=new test(10,20);
test ob3=new test(-1,-1);
System.out.println("ob1==ob2" + ob1.equals(ob2));
System.out.println("ob1==ob3" + ob1.equals(ob3));

DEPT OF ISE,SJCIT 2023 Page 18


MODULE 2 CLASSES and METHODS

Argument passing in java:


Arguments passing in Java refers to the mechanism of transferring data between methods or functions.
Arguments in Java are always passed-by-value.

java supports two types of arguments passing techniques

1. Call-by-value
2. Call-by-reference.

Pass/call-by-Value:

When a parameter is pass-by-value, the caller and the callee method operate on two different variables
which are copies of each other. Any changes to one variable don’t modify the other.
It means that while calling a method, parameters passed to the callee method will be clones of
original parameters. Any modification done in callee method will have no effect on the original
parameters in caller method.
public class test
{
void meth(int i,int j)
{
i*=2; Output:
j/=2; a and b before call:15 20
} a and b after call:15 20
}
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);


}

Pass/call-by-Reference:

When a parameter is pass-by-reference, the caller and the callee operate on the same object.
It means that when a variable is pass-by-reference, the unique identifier of the object is sent to the
method. Any changes to the parameter’s instance members will result in that change being made to the
original value.

DEPT OF ISE,SJCIT 2023 Page 19


MODULE 2 CLASSES and METHODS

class test1
{
int a,b;
test1(int i,int j)//constructor
{
a=i;
b=j;
}
void meth(test1 o)//object as the parameter
Output:
{ value. Output:
original
o.a *=2; ob.a and ob.b before call:15 20
o.b /=2; ob.a and ob.b after call: 30 10
}
}
public class CallByRef
{

public static void main(String[] args)


{
test1 ob=new test1(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);
}
}
Returning object:
 A method can return any type of data ,including class types that you create.
 In the following program, the incrbyten() method returns an object in which the value of a is ten
greater than it is in the invoking object.
class test
{
int a;
test (int i)
{
a=i;
}
test incrbyten()
{
test temp=new test(a+10);
return temp; Output:
} Ob1.a :2
} Ob2.a :12
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 );
}
}
Recursion:
 Recursion is the process of defining something in terms of itself.
DEPT OF ISE,SJCIT 2023 Page 20
MODULE 2 CLASSES and METHODS

 A method in java that calls itself is called recursive method.


 When writing recursive methods, you must have an if statement somewhere to force the method
to return without the recursive call being executed.
 The main advantages of recursive methods is that to create clearer and simpler versions of
several algorithms than can their iterative functions.

Example: factorial of a number


class factorial
{
int fact(int n)
{
int result; Output:
if(n==1) Factorial of 5 is:120
return 1; Factorial of 4 is:24
else Factorial of 3 is:6
result=n * factorial(n-1);
return result;
}
}
class recursion
{
public static void main(String[] args)
{
factorial f= new factorial();
System.out.println("Factorial of 5 is: "+factorial(5));
System.out.println("Factorial of 4 is: "+factorial(4));
System.out.println("Factorial of 3 is: "+factorial(3));
}
}

Access Modifiers (Access Specifiers)


 Access control controls which parts of the code access the members of a class.
 By controlling the access ,you can prevent misuse of the data.
 The access modifier’s in Java specifies the accessibility or scope of a field, method, constructor, or
class.
 We can change the access level of fields, constructors, methods, and class by applying the access
modifier on it.

Types:
 Default
 Public
 Private
 Protected

DEPT OF ISE,SJCIT 2023 Page 21


MODULE 2 CLASSES and METHODS

Access within within outside package by subclass outside


Modifier class package only package

Public Y Y Y Y

Private Y N N N

Protected Y Y Y N

Public:
 The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
 It has the widest scope among all other modifiers.

Private :
The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Protected:
 The protected access modifier is accessible within package and outside the package but through
inheritance only.
 The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Default:
 The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

class test
{
int a;//default access
public int b;//public access
Default:
private int c;// private access
void setc(int i)
Default:
{
c=i;
}
int getc()
{
return c;
}
}
class accesstest
{
public static void main(String args[])
{
test ob=new test();
//a and b can access directly
ob.a=10;
ob.b=20;

ob.c=100;//error
//you must access c through its method
ob.setc(100);;
System.out.println("a,b,and c:"+ob.a +"" + ob.b + "" + ob.getc());
DEPT OF ISE,SJCIT 2023 Page 22
}
}
MODULE 2 CLASSES and METHODS

Nested and Inner 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.
 The most important 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.
 The inner class does not have exist independently of outer class.
 The following program illustrates how to define and use an inner class.

public class Temp


{
int a=10;
class inner
{
void display( )
{
System.out.println("value of a is "+a);
}
}
void test( )
{
inner obj=new inner();
obj.display();
} Output:
public static void main( String args[ ] ) value of a is 10
{
Temp obj=new Temp();
obj.test();
}
}

Qp)What are the uses of final, explain with examples?


 A variable can be declared as final.
 Final variable is initialized when it is declared.
 It is a common coding convention to choose all uppercase identifiers for final variables.
 A final variable is like a constant.
 The keyword final has three uses.
a. It can be used to create the equivalent of a named constant.
b. to Prevent Overriding
c. to Prevent Inheritance
create the equivalent of a named constant:
example: final float PI=3.141f;
final int MAX=10;
final int FILE_NEW=1;
final int FILE_OPEN=2;

DEPT OF ISE,SJCIT 2023 Page 23

You might also like