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

JAVA Classes

Uploaded by

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

JAVA Classes

Uploaded by

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

CLASSES & OBJECTS

OBJECT
• An entity that has state and behavior is known as an object.
• e.g. pen, bike, box, table, car etc.
• An object has three characteristics:
• state: represents data (value) of an object.
• behavior: represents the behavior (functionality) of an object.
• Identity:
⮚ Object identity is typically implemented via a unique ID.
⮚ The value of the ID is not visible to the external user.
⮚ But, it is used internally by the JVM to identify each object uniquely.

For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.

Object is an instance of a class. Class is a template from which objects are created.
CLASS
• A class is a group of objects that has common properties. Class is a template from
which objects are created .
• Class forms the basis for object oriented programming
• Any concept to implement must be encapsulated in A CLASS
• General form of class deifintion :
class classname
{
type variable1;
type variable2;
…….
type methodname1(parameter-list)
{
//body of the method
}
type methodname2(parameter-list)
{
//body of the method
}
}
• The data or variables, defined within a class are called instance variables
• Each instance of the class contains its own copy of these variables
• Thus the data of one object is unique and separate from the data of another

• The methods and variables within a class are collectively called as members of the
class
Example:- class Box
{
double width;
double height;
double depth;
}
• To create an object of this class,
Box box1=new Box();
• To access the members, use dot operator
box1.width=10;
DEMONSTRATE A SIMPLE CLASS
class Box
System.out.println("Volume is "+volume);
{
}
double width;
}
double height;
double depth;
}
class BoxExample
{ OUTPUT
public static void main(String args[]) D:\merin\classes>java BoxExample
{ Volume is 3000.0
Box box1=new Box();
double volume;
box1.width=10;
box1.height=15;
box1.depth=20;
volume=box1.width*box1.height*box1.depth;
DEMONSTRATE TWO OBJECTS OF A CLASS
class BoxExample2 box2.height=3;
{ box2.width=6;
public static void main(String args[]) box2.depth=9;
{
Box box1=new Box(); vol=box2.height*box2.width*box2.depth;
Box box2=new Box(); System.out.println("Volume of box2 is : "+vol);
double vol; }
}
box1.height=20; /*class Box can be written in a separate source file
box1.width=15; Box.java and compile it separately. To run,
box1.depth=10; execute BoxExample2 file*/

vol=box1.height*box1.width*box1.depth;
System.out.println("Volume of box1 is : "+vol);
OUTPUT
Volume of box1 is : 3000.0
Volume of box2 is : 162.0

• Each object has its own copy of instance variables.


• Changes to the instance variables of one object have no effect on the instance
variables of another
Declaring objects
• 2 step process:-
• Declare a variable of the class type
• Must acquire an actual physical copy of the object and assign it to that variable.
• The new operator dynamically allocates memory for an object and returns a reference
to it.

• Statement Effect
Box box1; null

box1

box1=new Box(); width


height
box1
depth

New object
METHODS
• General form:
type name(parameter-list)
{
//body of method
}

⮚Here type specifies the type of data returned by the method


⮚This can be any valid type
⮚If the method does not return any value, its return type must be void
⮚The name of the method is specified by name(any legal identifier)
⮚The parameter-list is a sequence of type and identifier pairs separated by
commas.
⮚If the method has no parameters, then the list will be empty
DEMONSTRATE CLASS WITH METHOD box1.height=20;
class Box box1.width=15;
{ box1.depth=10;
double height; box1.volume();
double width; box2.height=3;
double depth; box2.width=6;
void volume() box2.depth=9;
{ box2.volume();
System.out.print("Volume is : "); }
System.out.println(height*width*depth); }
}
}
class BoxMethod
{ OUTPUT
public static void main(String args[]) D:\merin\classes>java BoxMethod
{ Volume is : 3000.0
Box box1=new Box(); Volume is : 162.0
Box box2=new Box();
RETURNING A VALUE BY A METHOD
• The type of data returned by a method must be compatible with the return type
specified by the method.
• The variable receiving the value returned by a method must also be compatible
with the return type specified for a method
RETURNING A VALUE BY A METHOD box1.height=20;
class Box box1.width=15;
{ box1.depth=10;
double height; vol=box1.volume();
double width; System.out.println("Volume of first box is : "+vol);
double depth; box2.height=3;
double volume() box2.width=6;
{ box2.depth=9;
return (height*width*depth); vol=box2.volume();
} System.out.print("Volume of second box is : ”+vol);
} }}
class Boxreturn
{
public static void main(String args[])
{ OUTPUT
Box box1=new Box(); D:\merin\classes>java Boxreturn
Box box2=new Box(); Volume of first box is : 3000.0
double vol; Volume of second box is : 162.0
ADDING METHOD WITH PARAMETERS
• In the preceding examples, dimensions are set by using these statements:
box1.height=20;
box1.width=15;
box1.depth=10;
• Disadvantages of this style:
• Error prone-can easily forget to set a dimension
• The instance variables should be accessed only through methods defined by
their class in well-designed Java programs
METHOD WITH PARAMETERS
class Box
{
double height;
double width;
double depth;
double volume()
{
return (height*width*depth);
}
void setDimen(double h,double w,double d)
{
height=h;
width=w;
depth=d;
}
}
class BoxParameter
{
public static void main(String args[])
{
Box box1=new Box();
Box box2=new Box();
box1.setDimen(20,15,10);
box2.setDimen(3,6,10);

System.out.println("volume of first box is : "+box1.volume());


System.out.println("volume of second box is : "+box2.volume());
}
}
OUTPUT
D:\merin\classes>java BoxParameter
volume of first box is : 3000.0
volume of second box is : 180.0
CONSTRUCTORS
• Java allows objects to initialize themselves when they are created
• This automatic initialization is performed through the use of a
constructor
• A constructor initializes an object immediately upon creation
• It has the same name as the class in which it resides
• Syntax is similar to a method
• They have no return type, not even void
• Because the implicit return type of a class’ constructor is the class
type itself
• Note:-
• If there is no explicit constructor, then Java creates a default constructor for
the class
• It automatically initializes all instance variables to zero.
CONSTRUCTORS EXAMPLE
class Box
{
double height;
double width;
double depth;
Box()
{
System.out.println(“Initializing values”);
height=20;
width= 15;
depth=10;
}
double volume()
{
return(height*width*depth);
}
}
class Constructor
{
public static void main(String args[])
{
Box box1=new Box();
Box box2=new Box();
System.out.println("Volume of first box is : "+box1.volume());
System.out.println("Volume of second box is : "+box2.volume());
}
}
OUTPUT
D:\merin\classes>java Constructor
Initializing values
Initializing values
Volume of first box is : 3000.0
Volume of second box is : 3000.0
PARAMETERIZED CONSTRUCTOR
• To construct Box objects with different dimensions, the easy solution is to add
parameters to the constructor
class Box
{
double height;
double width;
double depth;
Box(double h,double w,double d)
{
height=h;
width= w;
depth=d;
}
double volume()
{
return(height*width*depth);
}
class ParameterConstructor
{
public static void main(String args[])
{
Box box1=new Box(20,15,10);
Box box2=new Box(3,6,9);
System.out.println("Volume of first box is : "+box1.volume());
System.out.println("Volume of second box is : "+box2.volume());
}
}

OUTPUT
D:\merin\classes>java ParameterConstructor
Volume of first box is : 3000.0
Volume of second box is : 162.0
this KEYWORD
• this can be used inside any method to refer to the current object
Box(double h,double w,double d)
{
this.height=h;
this.width= w;
this.depth=d;
}
This version of Box() operates exactly like the earlier version.
INSTANCE VARIABLE HIDING
• When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
Box(double height,double width,double depth)
{
this.height=height;
this.width= width;
this.depth=depth;
}
GARBAGE COLLECTION

• Deallocation of memory is done automatically by a technique known as garbage collection.

• 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.

• No need to explicitly destroy objects

• Garbage collection occurs occasionally during the execution of the program


The finalize() Method
• Sometimes an object will need to perform some action when it is destroyed
• By using finalization, specific actions can be defined that will occur when an
object is to be reclaimed by the garbage collector
• General form:
protected void finalize()
{
//finalization code
}
Here the keyword protected is a specifier that prevents access to finalize() by code
defined outside its class
• Inside the finalize() method, we can specify those actions that must be performed
before an object is destroyed
• It is called only just prior to garbage collection.
• Not called when an object goes out of scope.
AN APPLICATION USING CLASS-STACK else
class Stack {
{ top++;
int stack[]=new int[10]; stack[top]=i;
int top; }
Stack() }
{ int pop()
top=-1; {
} if(top==-1)
void push(int i) {
{ System.out.println("Stack is empty");
if(top==9) return 0;
{ }
System.out.println("Stack is full"); else
} {
return(stack[top--]);
}
}
}
class StackTest for(i=0;i<10;i++)
{ {
public static void main(String args[]) System.out.print(" "+st1.pop());
{ }
int i; System.out.println();
Stack st1=new Stack(); System.out.println("Contents of second stack");
Stack st2=new Stack(); for(i=0;i<10;i++)
for(i=0;i<10;i++) {
{ System.out.print(" "+st2.pop());
st1.push(i); }
} }
for(i=100;i<110;i++) }
{ OUTPUT
st2.push(i); D:\merin\classes>java StackTest
} Contents of first stack
System.out.println("Contents of first stack"); 9 8 7 6 5 4 3 2 1 0
Contents of second stack
109 108 107 106 105 104 103 102 101 100
OVERLOADING METHODS
• Possible to define two or more methods within the same class that
share the same name as long as the parameter declarations are different.
• Then the methods are said to be overloaded and the process is referred
to as method overloading.
• One of the ways that Java implements 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
OVERLOADING METHODS
class Overload
{
void test()
{
System.out.println("No parameters");
}
void test(int a)
{
System.out.println("Value of a : "+a);
}
void test(int a ,int b)
{
System.out.println("Value of a : "+a+"\nValue of b : "+b);
}
double test(double a) OUTPUT
{ D:\merin\classes>java ExampleOverload
System.out.println("Value of a : "+a); No parameters
return a*a; Value of a : 1
} Value of a : 100
} Value of b : 200
class ExampleOverload Value of a : 123.25
{ Square value is : 15190.5625
public static void main(String args[])
{

Overload o1=new Overload();


o1.test();
o1.test(1);
o1.test(100,200);
System.out.println("Square value is : " +o1.test(123.25));
}
}
AUTOMATIC TYPE CONVERSIONS APPLY TO OVERLOADING
class Overload
{
void test()
{
System.out.println("No parameters");
}
void test(int a ,int b)
{
System.out.println("Value of a : "+a+"\nValue of b : "+b);
}
void test(double a)
{
System.out.println("Inside test with double");
System.out.println("Value of a : "+a);
}
}
class ExampleOverload2
{
public static void main(String args[])
{

Overload o1=new Overload();


o1.test();
o1.test(100,200);
o1.test(1); OUTPUT
o1.test(123.25); D:\merin\classes>java ExampleOverload2
} No parameters
} Value of a : 100
Value of b : 200
Inside test with double
Value of a : 1.0
Inside test with double
Value of a : 123.25
Method overloading supports polymorphism
• It is one way that Java implements the one interface, multiple methods
• In languages that do not support method overloading, there are usually
3 or more versions of the same function each with a slightly different
name
• Ex:- In C, 3 functions to calculate absolute value
• abs() -integer value
• labs()- long integer
• fabs()-float value
• Makes the situation more complex
• Java have only one function name for finding absolute value.
• abs() method of Math class
• It allows the related methods to be accessed by use of a common
name.
• Thus the name abs represents the general action which is being
performed.
• Through the application of polymorphism, several names have been
reduced to one.

Note:- Although we can use the same name to overload unrelated


functions, we should not do it.
CONSTRUCTOR OVERLOADING
Box(double h,double w, double d)
class Box
{
{
width=w;
double height;
height=h;
double width;
depth=d;
double depth;
}
Box()
double volume()
{
{
width=-1;
return width*height*depth;
height=-1;
}
depth=-1;
}
}
}
Box(double l)
{
height=width=depth=l;
}
class ConstructorOverload
{
public static void main(String args[])
{
Box b1=new Box();
Box b2=new Box(20,15,10);
Box b3=new Box(10);
System.out.println("Volume of first cube is : "+b1.volume());
System.out.println("Volume of second cube is : "+b2.volume());
System.out.println("Volume of third cube is : "+b3.volume());
}

OUTPUT
Volume of first cube is : -1.0
Volume of second cube is : 3000.0
Volume of third cube is : 1000.0
PASSING OBJECT AS PARAMETER
class Test
{ class PassObject
int a,b; {
Test(int i,int j) public static void main(String args[])
{ {
a=i; Test t1=new Test(10,20);
b=j; Test t2=new Test(100,200);
} Test t3=new Test(10,20);
boolean equals(Test obj) boolean flag;
{ flag=t1.equals(t2);
if (obj.a==a && obj.b==b) System.out.println("t1 == t2 : "+flag);
return true; flag=t1.equals(t3);
else System.out.println("t1 == t3 : "+flag);
return false; flag=t2.equals(t3);
} System.out.println("t2 == t3 : "+flag);
} }
}
OUTPUT
t1 == t2 : false
t1 == t3 : true
t2 == t3 : false

• Most common use of object parameters involves constructors.

• When we want to construct a new object so that it is initially the same as an existing
object
PASSING OBJECTS TO CONSTRUCTOR
Box(double h,double w, double d)
class Box
{
{
width=w;
double height;
height=h;
double width;
depth=d;
double depth;
}
Box()
Box(Box obj)
{
{
width=-1;
width=obj.width;
height=-1;
height=obj.height;
depth=-1;
depth=obj.depth;
}
}
Box(double l)
double volume()
{
{
height=width=depth=l;
return width*height*depth;
}
}
}
class PassObjectConstructor
{
public static void main(String args[])
{
Box b1=new Box();
Box b2=new Box(20,15,10);
Box b3=new Box(10);
Box b4=new Box(b2);
System.out.println("Volume of first cube is : "+b1.volume());
System.out.println("Volume of second cube is : "+b2.volume());
System.out.println("Volume of third cube is : "+b3.volume());
System.out.println("Volume of fourth cube is : "+b4.volume());
}
} OUTPUT
Volume of first cube is : -1.0
Volume of second cube is : 3000.0
Volume of third cube is : 1000.0
Volume of fourth cube is : 3000.0
2 WAYS OF ARGUMENT PASSING
• There are two ways that a computer language can pass an argument to subroutine
1)call by value
2)call by reference
1)call by value
⮚The value of the argument is copied to the formal parameter of the subroutine
⮚Therefore changes made to the parameter have no effect on the argument
⮚When a simple type is passed to a method, it is passed by a vlaue

2)Call by reference
⮚A reference to an argument is passed to the parameter.
⮚Changes made to the parameter will affect the argument used to call the subroutine
⮚Objects are passed by reference
CALL BY VALUE
class Test
{ OUTPUT
void modify(int i,int j) D:\merin\classes>java CallValue
{ Before modify function :a= 10 b= 20
i*=2; After modify function :a= 10 b= 20
j/=2;
}}
class CallValue
{
public static void main(String args[])
{
Test t1=new Test();
int a=10,b=20;
System.out.println("Before modify function :a= "+a+" b= "+b);
t1.modify(a,b);
System.out.println("After modify function :a= "+a+" b= "+b);
}
CALL BY REFERENCE
class Test
{
int a,b;
Test(int i,int j)
{
a=i;
b=j;
}
void modify(Test obj)
{
obj.a=obj.a*2;
obj. b=obj.b/2;
}
}
class CallReference
{
public static void main(String args[])
{
Test t1=new Test(100,20);
System.out.println("Before modify function :a= "+t1.a+" b= "+t1.b);
t1.modify(t1);
System.out.println("After modify function :a= "+t1.a+" b= "+t1.b);
}
}

OUTPUT
D:\merin\classes>java CallReference
Before modify function :a= 100 b= 20
After modify function :a= 200 b= 10
RETURNING OBJECTS class Return
• A method can return any type of data, {
including class types. public static void main(String args[])
{
class Test Test t=new Test(10);
{ Test t3;
int a; t3=t.increment();
Test(int i) System.out.println("t : "+t.a);
{ System.out.println("t3 : "+t3.a);
a=i; }
} }
Test increment()
{ OUTPUT
Test t2=new Test(a*2); D:\merin\classes>java Return
return t2; t : 10
} t3 : 20
}
RECURSION
• Process of defining something in terms of itself
• A method that calls itself is said to be recursive
class Recursion
{
class Factorial public static void main(String args[])
{
{
int fact(int n) Factorial f1=new Factorial();
{
System.out.println("Factorial of 3: "+f1.fact(3));
if(n==1) System.out.println("Factorial of 8: "+f1.fact(8));
return 1;
}
else
}
return (n*fact(n-1) );
}
} OUTPUT
D:\merin\classes>java Recursion
Factorial of 3: 6
Factorial of 8: 40320
• When a method calls itself, new local variables and parameters are
allocated storage on the stack
• Then the method is executed with these new variables from the start
Disadvantage:-
• Recursive versions may execute a bit more slowly than the iterative
equivalent
• Due to the added overhead of the function calls
• Possibility for the stack overflow
Advantage :-
• Can be used to create clearer and simpler versions of several
algorithms
Eg:-Quicksort algorithm
• Some programmers seem to think recursively than iteratively
• Note:-
⮚When writing recursive methods, there must be an if statement
somewhere to force the method to return (without the recursive
call being executed)
⮚If it is missing, when we make a call, it will never return
DISPLAY THE ELEMENTS OF AN ARRAY USING RECURSION
class Array
{
int a[];
Array(int i)
{
a=new int[i];
}
void display(int n)
{
if(n==0) return;
else
{
display(n-1);
System.out.println("Index["+(n-1)+"] : "+a[n-1]);
}
}
}
class Recursion2 OUTPUT
{
public static void main(String args[]) Index[0] : 0
{ Index[1] : 100
Array obj=new Array(10); Index[2] : 200
for(int i=0;i<10;i++) Index[3] : 300
{ Index[4] : 400
obj.a[i]=i*100; Index[5] : 500
} Index[6] : 600
obj.display(10); Index[7] : 700
} Index[8] : 800
} Index[9] : 900
ACCESS CONTROL
• Through encapsulation, we can control what parts of a program can
access the members of a class
• Ex:- allowing access to data only through well defined methods can
prevent the misuse of data
• Access specifiers:-
⮚Public
⮚Private
⮚Protected(applies only when inheritance is involved)
⮚default access level
• When a member is public, it can be accessed by any other code
• When a member is private, it can be accessed only by other members
of its class
• When no access specifier is used, then by default the member is
public within its own package, but cannot be accessed outside of its
package
DIFFERENCE BETWEEN THE PRIVATE AND PUBLIC
class Test public static void main(String args[])
{ {
int a; Test t=new Test();
public int b; t.a=10;
private int c; t.b=20;
void setc(int i) //t.c=30; error,c has private access
{ t.setc(30);
c=i; System.out.println("Value of a : "+t.a);
} System.out.println("Value of b : "+t.b);
int getc() System.out.println("Value of c : "+t.getc());
{ }
return c; }
}
} OUTPUT
class Access Value of a : 10
{ Value of b : 20
Value of c : 30
STACK APPLICATION WITH PRIVATE MEMBERS else
class Stack {
{ top++;
private int stack[]=new int[10]; stack[top]=i;
private int top; }
Stack() }
{ int pop()
top=-1; {
} if(top==-1)
void push(int i) {
{ System.out.println("Stack is empty");
if(top==9) return 0;
{ }
System.out.println("Stack is full"); else
} {
return(stack[top--]);
}
}
}
class StackTest System.out.println("Contents of first stack");
{ for(i=0;i<10;i++)
public static void main(String args[]) {
{ System.out.print(" "+st1.pop());
int i; }
Stack st1=new Stack(); System.out.println();
Stack st2=new Stack(); System.out.println("Contents of 2nd stack");
for(i=0;i<10;i++) for(i=0;i<10;i++)
{ {
st1.push(i); System.out.print(" "+st2.pop());
} }
for(i=100;i<110;i++) }
{ }
st2.push(i);
OUTPUT
}
Contents of first stack
9876543210
Contents of 2nd stack
109 108 107 106 105 104 103 102 101 100
STATIC
• When we want to define a class member that will be used independently
of any object of that class
• When a member is declared static, it can be accessed before any objects
of its class are created
• main() is declared as static because it must be called before any objects
exist
• Can declare both variables and methods as static
• Instance variables declared as static are global variables.
⮚When objects of its class are declared, no copy of a static variable is made.
⮚All objects share the same static variable
• Methods declared as static have restrictions:
⮚Can only call other static methods
⮚Must only access static data
⮚Cannot refer to this or super
STATIC VARIABLE EXAMPLE1 class ExampleStatic2
class Student {
{ public static void main(String args[])
int rollno; {
String name; Student s1=new Student(13,"Avinash");
static String college="VI"; Student s2=new Student(14,"Abhishek");
Student(int r,String n) Student s3=new Student(15,"Ajay");
{ s1.display();
rollno=r; s2.display();
name=n; s3.display();
} }
void display() }
{
System.out.println(" "+rollno+" "+name+" "+college );
} OUTPUT
} 13 Avinash VI
14 Abhishek VI
15 Ajay VI
STATIC VARIABLE EXAMPLE2
class Test OUTPUT
{ VALUE OF COUNTER IS : 3
static int count=0;
Test()
{
count++;
}
}
class ExampleStatic3
{
public static void main(String args[])
{
Test t1=new Test();
Test t2=new Test();
Test t3=new Test();
System.out.println("VALUE OF COUNTER IS : "+Test.count);
}
}
STATIC METHOD
class Student
{
int rollno;
String name;
static String college="VI";
Student(int r,String n)
{
rollno=r;
name=n;
}
static void change(String s)
{
college=s;
}
void display()
{
System.out.println(rollno+" "+name+" "+college );
}
}
class ExampleStatic4
{
public static void main(String args[])
{
Student.change("VIT");
Student s1=new Student(13,"Avinash");
Student s2=new Student(14,"Abhishek");
Student s3=new Student(15,"Ajay");
s1.display(); OUTPUT
s2.display(); 13 Avinash VIT
s3.display(); 14 Abhishek VIT
} 15 Ajay VIT
}
final
• A variable can be declared as final.
• Its contents cannot be modified
• Must initialize a final variable when it is declared
Eg:- final int FILE_OPEN=1;
• Convention to use uppercase identifiers for final variables
• Variables declared as final do not occupy memory on a per-
instance basis
ARRAY
• Array is implemented as object in java
• Length is a special array attribute that always hold the size of the array
class ArrayObj
{
public static void main(String args[])
{
int a[]=new int[10];
int b[]={1,2,3,4,5,6};

System.out.println("Length of a is : "+a.length);
System.out.println("Length of b is : "+b.length);
}
} OUTPUT
Length of a is : 10
Length of b is : 6
USING LENGTH ARRAY MEMBER IN STACK CLASS
class Stack
{
private int stack[];
private int top;
Stack(int size)
{
top=-1;
stack=new int[size];

}
void push(int i)
{
if(top==stack.length-1)
{
System.out.println("Stack is full");
}
else
{
top++;
stack[top]=i;
}
}
int pop()
{
if(top==-1)
{
System.out.println("Stack is empty");
return 0;
}
else
{
return(stack[top--]);
}
}
}
class StackLength
{
public static void main(String args[])
{
int i; System.out.println("Contents of first stack");
Stack st1=new Stack(5); for(i=0;i<5;i++)
Stack st2=new Stack(8); {
for(i=0;i<5;i++) System.out.print(" "+st1.pop());
{ }
st1.push(i); System.out.println();
} System.out.println("Contents of second stack");
for(i=100;i<108;i++) for(i=0;i<8;i++)
{ {
st2.push(i); System.out.print(" "+st2.pop());
} }

}
}
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.
• If class B is defined within class A, then B is known to A, but not
outside of A
• A nested class has access to the members, including private
members, of the class in which it is nested
• But the enclosing class does not have access to the members of the
nested class
• There are two types of nested classes:
• Static
• Non static
• Static nested class
• is a nested class which is a static member of the outer class
• It can access static data members of outer class including private.
• Static nested class cannot access non-static (instance) data member or
method.

The syntax of static nested class is as follows:


class MyOuter
{
static class Nested_Demo{ }
}
• Non-static nested class (inner class)
• It has access to all of the variables and methods of its outer
class and can refer to them directly
• Inner class is fully within the scope of its enclosing class
DEMONSTRATE INNER CLASS public class NestedExample
class Outer {
{ public static void main(String[] args)
int outer_x=100; {
void test() Outer out=new Outer();
{ out.test();
Inner in=new Inner(); }
in.display();
} }
class Inner
{
void display()
{
System.out.println("value of outer_x :"+ outer_x);
} OUTPUT
} value of outer_x :100
}
class Outer INNER CLASS EXAMPLE2
{
int outer_x=100;
void test()
{
Inner in=new Inner();
in.display();
//System.out.println("value of inner_y :"+ inner_y); error,y is not known to outer class
}
class Inner
{
int inner_y=22;
void display()
{
System.out.println("value of outer_x :"+ outer_x);
System.out.println("value of inner_y :"+ inner_y);
}
}
}
public class NestedExample
{
public static void main(String[] args)
{
Outer out=new Outer();

out.test();
}

OUTPUT
value of outer_x :100
value of inner_y :22
STRING CLASS
• Most commonly used class in Java’s library
• Every string is an object of type String
• Java defines an operator + for concatenation of two strings

class ExampleString
{
public static void main(String args[])
{
String s1="FIRST";
String s2="SECOND";
String s3=s1+" AND "+s2; OUTPUT
System.out.println(s1); FIRST
System.out.println(s2); SECOND
System.out.println(s3); FIRST AND SECOND
}
}
USE OF SOME STRING METHODS
General form: boolean equals(String object)
int length()
char charAt(int index)
class ExampleString2
{
public static void main(String args[])
{
String s1="FIRST";
String s2="SECOND";
String s3=s1;
System.out.println("STRINGS ARE :");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println("Length of first string is : "+s1.length());
System.out.println("Character at index 3 of first string is :"+s1.charAt(3));
if(s1.equals(s2))
System.out.println("first=second");
else
System.out.println("first not equal to second");
if(s1.equals(s3))
System.out.println("first=third");
else
System.out.println("first not equal to third");

} OUTPUT
} STRINGS ARE :
FIRST
SECOND
FIRST
Length of first string is : 5
Character at index 3 of first string is :S
first not equal to second
first=third
COMMAND LINE ARGUMENTS
• When we want to pass information into a program when we run it.
• A command line argument is the information that directly follows the
program’s name on the command line when it is executed
class Command
{
public static void main(String args[])
{
System.out.println("THE ARGUMENTS ARE:");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
}
}
OUTPUT
D:\merin\classes>java Command hello welcome to this world
THE ARGUMENTS ARE:
hello
welcome
to
this
world

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy