JAVA Classes
JAVA Classes
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
• Statement Effect
Box box1; null
box1
New object
METHODS
• General form:
type name(parameter-list)
{
//body of method
}
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
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
• 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.
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