Você está na página 1de 88

What is class?

What is class?
Class is a collection of data members and member functions.
Now what are data members?
Data members are nothing but simply variables that we declare inside the class so it called
data member of that particular class.
Now what are member functions?
Member functions are the function or you can say methods which we declare inside the class
so it called member function of that particular class.
The most important thing to understand about a class is that it defines a new data type.
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. Because an
object is an instance of a class, you will often see the two words object and instance used
interchangeably.
Syntax of class:
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
}
}
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.

The data, or variables, defined within a class are called instance variables. The code is
contained within methods.
NOTE : C++ programmers will notice that the class declaration and the implementation of
the methods are stored in the same place and not defined separately.
EX.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

public class MyPoint


{
int x = 0;
int y = 0;
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}

public static void main(String args[])


{
MyPoint obj; // declaration
obj = new MyPoint(); // allocation of memory to an object
obj.x=10; //access data member using object.
obj.y=20;
obj.displayPoint(); // calling a member method
}

Output :
Printing the coordinates
10 20
Here x and y are data members of class MyPoint and displayPoint() is a member function of
the same class.
In above program we can take as many objects as we want.
From the above program one thing we should keep in mind that when we want to access
data member or methods of class we have to write objectname.member name
Syntax:
accessing data member of the class: objectname.datamember name;
accessing methods of the class: objectname.method name();
So for accessing data of the class: we have to use (.) dot operator.

NOTE: we can use or access data of any particular class without using (.) dot operator from
inside that particular class only.
How to declare object of class in java?
The program we gave in previous topic from that we can easily learn that how object is
going to declare and define for any class.
Syntax of object:
classname objectname;

\\ declaration of object.

objectname = new classname();

\\ allocate memory to object (define object).

or we can directly define object like this


classname objectname = new classname();
Now let us look one class which has two different object.
?
1

class Box

double width;

double height;

double depth;

class BoxDemo2

9
10

public static void main(String args[])


{

11

Box mybox1 = new Box();

12

Box mybox2 = new Box();

13

double vol;

14

// assign values to mybox1's instance variables

15

mybox1.width = 10;

16

mybox1.height = 20;

17

mybox1.depth = 15;

18

/* assign different values to mybox2's instance variables */

19

mybox2.width = 3;

20

mybox2.height = 6;

21

mybox2.depth = 9;

22

// compute volume of first box

23

vol = mybox1.width * mybox1.height * mybox1.depth;

24

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

25

// compute volume of second box

26

vol = mybox2.width * mybox2.height * mybox2.depth;

27

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

28
29

}
}

Output :

Volume is 3000.0
Volume is 162.0
From the above program we can understand that 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.
Assigning Object Reference Variables :

Suppose

Box b1 = new Box();


Box

b2

b1;

Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1.

Here we did not use new keyword for b2 so 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.
NOTE: When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference.

Introduction to method
As we all know that, classes usually consist of two things instance variables and methods.
Here we are going to explain some fundamentals about methods.
So we can begin to add methods to our classes.
Methods are defined as follows
Return type
Name of the method
A list of parameters
Body of the method.
Syntax:
return type method name (list of parameters)
{
Body of the method

}
return type specifies the type of data returned by the method. This can be any valid data
type including class types that you create.
If the method does not return a value, its return type must be void, Means you can say that
void means no return.
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.
The method name is any legal identifier.
The list of parameter is 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.
If the method has no parameters, then the parameter list will be empty.
Let us look at one example of class which have methods and data members both.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
void volume()
// display volume of a box
{
System.out.print("Volume is : ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(Enter Box Width : );
box1.width = s.nextDouble();
System.out.print(Enter Box Height : );
box1.height = s.nextDouble();
System.out.print(Enter Box Depth : );
box1.depth = s.nextDouble();
// display volume of box1

26
27
28

box1.volume(); // calling the method volume

Output:
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Here width, height and depth are data members of class Box and void volume() is method
of class Box.
Here method has no parameter and no return value.
Now let us look at same program but in different way.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
double vol;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(Enter Box Width : );
box1.width = s.nextDouble();
System.out.print(Enter Box Height : );
box1.height = s.nextDouble();
System.out.print(Enter Box Depth : );
box1.depth = s.nextDouble();
// display volume of box1
vol = box1.volume(); // calling the method volume
System.out.println("Volume is : " +vol);
}
}

Output:
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Here in above program volume() method has return type double so we took one vol
variable. It is a local variable of class BoxDemo and it catch the returned value by volume
method of class Box.
One thing must keep in mind that the data type of vol and return type of volume() method
always be same.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
double volume(double w, double h, double d)
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
double vo,wth,ht,dth;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(Enter Box Width : );
wth = s.nextDouble();
System.out.print(Enter Box Height : );
ht = s.nextDouble();
System.out.print(Enter Box Depth : );
dth = s.nextDouble();
// display volume of box1
vol = box1.volume(wth,ht,dth); // calling the method volume
System.out.println("Volume is : " +vol);
}
}

Output:
Enter Box Width : 15

Enter Box Height : 20


Enter Box Depth : 10
Volume is : 3000.00

Here in above program volume() method has three parameters as well as double return
type.
Here we took three extra local variables in class BoxDemo and pass them in function calling.
One thing must keep in mind that in defining and calling of method, the sequence of data
type of parameter must be same in both.

Constructor
Java supports a special type of methods, called constructor that enables an object to
initialize itself when it is created.
Constructors have the same name as the class it-self.
Constructors do not specify a return type, not even void. This is because they return the
instance of the class itself.
A constructor is automatically called when an object is created.
Syntax:
Constructor_name([arguments])
{
// body
}
Constructors are generally of two types.

1.
?
1

1.

Non-Parameterized

2.

Parameterized

Non-Parameterized:

// Non - parameterised constructor

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

class Point1
{
int x;
int y;
Point1() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
Point1 p1 = new Point1(); // constructor will be call automatically from here
p1.display();
}
}

Output:
-----Printing the coordinates----10 20
2.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Parameterized:
// parameterised constructor
import java.util.Scanner;
class Point2
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
int i,k;

23
24
25
26
27
28
29
30
31

Scanner s = new Scanner(System.in);


System.out.print("Enter int value for i : ");
i = s.nextInt();
System.out.print("Enter int value for k : ");
k = s.nextInt();
Point2 p1 = new Point2(i,k);
p1.display();

Output:
Enter int value for i : 10
Enter int value for k : 20
-----Printing the coordinates----10 20
Keywords
We have already seen one keywords table in our first chapter.
But here we are going to learn few regularly used keywords.
1. new
2. this
3. static
4. super
5. final
The super and final keywords will demonstrate in further chapter.
new:
The new keyword dynamically allocates memory for an object.
Syntax:
claas_name object _name = new class_name();
EX.
Box b1 = new Box();
Box b2 = new Box();
We have already seen so many programs in which we used new keyword for creating
objects.

this:
This keyword is the name of a reference that refers to a calling object itself.
one common use of the this keyword is to reference a class` hidden data fields.
You can have local variables, including formal parameters to methods which overlap with the
names of the class` instance variables.
The local variable hides the instance variable so we use this keyword.
Another common use of this keyword is to enable a constructor to invoke another
constructor of the same class.
java requires that the this(arg-list) statement appear first in the constructor before any
other statements.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

public class This_demo


{
public static void main(String[] args)
{
abc a1 = new abc();
//call non parameterize constructor
}
}
class abc
{
int x,y;
abc()
{
this(10,20); //this will call another constructor
}
abc(int x,int y)
{
this.x=x+5;
//it will set class` member x
this.y=y+5;
//it will set class` member y
System.out.println("local method`s x = " +x);
System.out.println("local method`s y = " +y);
Print_data();
}
public void Print_data()
{
System.out.println("x = " +x);
System.out.println("y = " +y);
}
}

Output :
local method`s x = 10
local method`s y = 20
x = 15
y = 25
static :
A class member must be accessed with the use of an object of its class but sometimes we
want to define a class member that will be used independently without creating any object
of that class.
It is possible in java 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.
one 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 object exist.
Instance variables declared as static are actually, 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.
Method declared as static have several restrictions:
1.

Can call only other static methods.

2.

Only access static data.

3.

Can not refer to this or super in any way.

One can also declare a static block which gets executed exactly once, when the class is first
loaded.
EX :
?
1
2

public class Static_Demo


{

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

public static void main(String[] args)


{
display(40); //call static method
}
static int i = 5;
static int j;
int k = 10;
static void display(int a)
{
System.out.println("a = "+a); // here a = 40
System.out.println("i = "+i); // here i = 5
System.out.println("j = "+j); // here j = 50( because of static block j = i * 10 = 5 * 10 =50 )
//System.out.println("k = "+k); //can,t make a static reference to the non-static field k
}
static
{
System.out.println("Static block initialized..........");
j = i * 10;
}

Output :
Static block initialized..........
a = 40
i=5
j = 50

Access Control

One can control what parts of a program can access the member of a class. By controlling
access, one can prevent misuse.
For Example, allowing access to data only through a well-defined set of methods, one can
prevent misuse of that data. Thus,
when correctly implemented, a class creates black box.
How a member can be accessed is determined by the access specifier that modifies its
declaration.
Java provides a set to access specifiers. Some aspects of access control are related to
inheritance or packages.
Javas access specifiers are:

public:
o When a member of a class is specified by the public specifier, then that
member can be accessed by any other code.
o The public modifier makes a method or variable completely available to all
classes.
o

Also when the class is defined as public, it can be accessed by any other class.

private:
o

To hide a method or variable from other classes, private modifier is used.

o A private variable can be used by methods in its own class but not by objects
of any other class.
o

Neither private variables nor private methods are inherited by subclass.

o The only place these variables and methods can be seen is from within their
own class.
protected:
o

protected applies only when inheritance is involved.

o If you want to allow an element to be seen outside your current package, but
only to classes that are inherited from your class directly, then declare that
element as protected.
default:
o We have seen that when no access control modifier is specified, it is called as
default access.
o

Classes written like this are not accessible in other package.

o Any variable declared without a modifier can be read or changed by any other
class in the same package.
o Any method declared the same way can be called by any other class in the
same package.
o
o

When a member does not have an explicit access specification,


it is visible to subclasses as well as to other classes in the same package.

The following table summarizes the levels of access control.

Access

Public

Protected

Default

Private

From the same


class

Yes

Yes

Yes

Yes

From any class


in the same
package

Yes

Yes

Yes

No

From any class


outside the
package

Yes

No

No

No

From a sub class in the


same package

Yes

Yes

Yes

No

From a sub class outside


the same
package

Yes

Yes

Yes

No

Method overloading in java:


Method overloading:
A class can contain any number of methods. Methods can be with parameter and without
parameter.
The parameter in a method are called type signature.
It is possible in java to define two or more methods within the same class that share the
same name, but with different parameter declarations (type signatures).
When this is the case, the methods are said to be overloaded, and the process is referred to
as method overloading.
Overloading methods demonstrate the concept of 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 call.
Thus, overloaded methods must differ in the type and/or number of their parameters.
Overloaded methods may have different return types.
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.
EX :
?
1

public class MethodOver

int n1;

int n2;

MethodOver()

n1 = 10;

n2 = 20;

10

void square()

11

12

System.out.println("The Square is " + n1 * n2);

13

14

void square(int p1)

15

16

n1 = p1;

17
18
19

System.out.println("The Square is " + n1 * n2);


}
void square(int p1, int p2)

20

21

n1 = p1;

22

n2 = p2;

23

System.out.println("The Square is " + n1 * n2);

24

25

public static void main(String args[])

26

27

MethodOver obj1 = new MethodOver();

28

obj1.square(); //call non parameterise method

29

obj1.square(4);

30

obj1.square(7,8); //call method which has 2 argument

31
32

//call method which has 1 argument

}
}

Output :

The Square is 200


The Square is 80
The Square is 56
You can see that here we have 3 square methods with different argument.
Its called method overloading.

Constructor overloading in java:


Along with method overloading, we can also overload constructors. Constructors having the
same name with different parameter list is called constructor overloading.
EX :
?

class Point

int x;

int y;

Point(int a, int b)

x = a;

y = b;

10
11

12
13

class Circle

14

15

int originX;

16

int originY;

17

int radius;

18
19

//Default Constructor

20
21

Circle()

22

23

originX = 5;

24

originY = 5;

25

radius = 3;

26
27

28
29

// Constructor initializing the coordinates of origin and the radius.

30
31

Circle(int x1, int y1, int r)

32

33

originX = x1;

34

originY = y1;

35

radius = r;

36
37

38
39
40

Circle(Point p, int r)

41

42

originX = p.x;

43

originY = p.y;

44

radius = r;

45

46
47

void display()

48

49

System.out.println("--Center at " + originX + " and " + originY);

50

System.out.println("Radius = " + radius);

51

52
53

public static void main(String args[])

54

55
56

Circle c1 = new Circle();

57

Circle c2 = new Circle(10,20,5);

58

Circle c3 = new Circle(new Point(15,25),10);

59
60

c1.display();

61

c2.display();

62

c3.display();

63

64

Output :

--Center at 5 and 5
Radius = 3
--Center at 10 and 20
Radius = 5
--Center at 15 and 25
Radius = 10

Above program is quite complicated here i am giving you perfect flow of program.

First of all note one thing that new ClassName() this is a short syntax of creating object
of any class.

And we all know that when we create object the constructor of that class will be called
automatically.

So in our program first of all due to syntax Circle c1 = new Circle(); non
parameterize constructor will be called for object c1 so we get output like Center at 5 and 5
Radius = 3 in c1.display().

Next due to syntax Circle c2 = new Circle(10,20,5); constructor which has 3 arguments will
be called for object c2 so we get output like Center at 10 and 20 Radius = 5 in c2.display().

Now when we define object c3 our syntax is like Circle c3 = new Circle(new
Point(15,25),10); so first of all it will create object for Point class so constructor of point
class will be called and it will set parameter x and y.

Then constructor of circle class which has Point class object as an argument along with one
int argument will be called and set all parameter as per program and we get output like
Center at 15 and 25 Radius = 10 in c3.display().

We can also write

Point p1 = new Point(15,25);


Circle c3 = new Circle(p1,10);

This is how we can pass object as an argument in constructor.

We have already seen Call by reference in which we pass object as a method argument.
Now in next topic we will discuss about how you can return an object.
1. Passing Objects as a Parameter to Method.
We have seen that methods can take parameters as input and process them.
It is also common to pass objects as a parameter to methods.
?
1
2

class PassObj
{

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

int n1;
int n2;
// constructor
PassObj()
{
n1 = 0;
n2 = 0;
}
PassObj(int p1, int p2)
{
n1 = p1;
n2 = p2;
}

void multiply(PassObj p1)


{
int temp;
temp = p1.n1 * p1.n2;
System.out.println("Multiplication is " + temp);
}
public static void main(String args[])
{
PassObj obj1 = new PassObj(5,6);
PassObj obj2 = new PassObj();
obj2.multiply(obj1);
}

Output :
Multiplication is 30
2. Method overloading with object as a parameter.
?
1
class MetObjOv
2
{
3
int n1;
4
int n2;
5
6
// constructor
7
MetObjOv()
8
{
9
n1 = 0;
10
n2 = 0;
11
}
12
MetObjOv(int x, int y)
13
{
14
n1 = x;
15
n2 = y;
16
}
17
void multiply(MetObjOv p1)

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41

n1 = p1.n1;
n2 = p1.n2;
System.out.println("There is nothing to multiply ");
System.out.println("n1 = "+n1+"\tn2 = " +n2);

}
void multiply(MetObjOv p1, MetObjOv p2)
{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;

System.out.println("Multiplication of two objects ");


System.out.println("n1 = " + n1 + "\tn2 = " + n2 );

public static void main(String args[])


{
MetObjOv obj1 = new MetObjOv(5,6);
MetObjOv obj2 = new MetObjOv(6,5);
MetObjOv obj3 = new MetObjOv();
obj3.multiply(obj1);
obj3.multiply(obj1, obj2);
}

Output :
There is nothing to multiply
n1 = 5 n2 = 6
Multiplication of two objects
n1 = 30 n2 = 30
3. Return an Object.
A method can return any type of data, including class type (object) that you create.
?
1
class RetObj
2
{
3
int n1;
4
int n2;
5
6
// constructor
7
RetObj()
8
{
9
n1 = 0;
10
n2 = 0;
11
}
12
RetObj(int x, int y)
13
{
14
n1 = x;
15
n2 = y;
16
}

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

RetObj multiply(RetObj p1, RetObj p2)


{
n1 = p1.n1 * p2.n1;
n2 = p1.n2 * p2.n2;
return (this);
}
void display()
{
System.out.println("An Example of returning an Object ");
System.out.println("n1 = "+n1+"\tn2 = " +n2);
}

public static void main(String args[])


{
RetObj obj1 = new RetObj(5,6);
RetObj obj2 = new RetObj(6,5);
RetObj obj3 = new RetObj();
obj3 = obj3.multiply(obj1, obj2);
obj3.display();
}

Output :
An Example of returning an Object
n1 = 30 n2 = 30
RetObj multiply(RetObj p1, RetObj p2) This is the syntax in our program which has return
type object.
obj3 = obj3.multiply(obj1, obj2); this is the syntax which calls method multiply and return
object, it will store in obj3.

Call by value
Now we all know that how to define and call the methods.
There are two types of calling method and those are
1. call by value
2. call by reference
Here we illustrate call by value and in next topic we will look at call by reference.
In call by value when we call any method we pass value as method parameter so changing
in local variables of the method doesn't`t affect the original variables of class.

This method copies the value of an argument into the formal parameter of the subroutine.
Therefore, changes made to the parameter of the subroutine have no effect on the
argument.
In java, when we pass a primitive type to a method, it is passed by value.
Thus, what occurs to the parameter that receives the argument has no effect outside the
method.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

public class CallBy_Value


{
public static void main(String[] args)
{
Value v = new Value(10,20);
System.out.println("a and b before call............");
System.out.println("a = "+v.a);
System.out.println("b = "+v.b);
v.call(v.a,v.b);
// CALL BY VALUE
System.out.println("a and b after call............");
System.out.println("a = "+v.a);
System.out.println("b = "+v.b);
}
}
class Value
{
int a,b;
Value(int i,int j)
{
a=i;
b = j;
}
void call(int a, int b)
{
a = a * 2;
b = b * 2;
}
}

Output :
a
a
b
a
a
b

and b before call............


= 10
= 20
and b after call............
= 10
= 20

You can see that after calling method we change value of a and b but it will not afect the
original value of class` members because of call by value.
We pass value v.a and v.b as parameter and it will change local method`s a and b variables.
Call by reference
Call by reference :
Here we pass reference as parameter in function calling.
We all know that reference means object so we pass object as parameter.
A reference to an argument (not value of argument) is passed to the parameter.
Inside the subroutine, this reference is used to access the actual argument specified in the
call.
This means that changes made to the parameters will affect the argument used to call the
subroutine.
When we pass an object to a method, the situation changes, because objects are passed by
call-by-reference.
When we create a variable of a class type, we are only creating a reference to an object.
Thus,
When you pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
This effectively means that objects are passed to method do affect the object used as an
argument.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14

public class CallBy_Reference


{
public static void main(String[] args)
{
Reference r = new Reference(10,20);
System.out.println("a and b before call............");
System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
r.call(r);
// CALL BY REFERENCE
System.out.println("a and b after call.............");
System.out.println("a = "+r.a);
System.out.println("b = "+r.b);
}
}

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Reference
{
int a,b;
Reference(int i,int j)
{
a=i;
b = j;
}
void call(Reference r)
{
r.a = a * 2;
r.b = b * 2;
}
}

Output :
a
a
b
a
a
b

and b before call............


= 10
= 20
and b after call.............
= 20
= 40

You can see that after calling method value of original a and b is changed because of call by
reference.
Here we pass "r" reference (Object) as parameter in method calling. So changes inside
method will affect original variable of class.
Recursion :
Recursion is the process of defining something in terms of itself.
When function call it self is called recursion.
A method that calls itself is said to be recursive.
EX :
?
1
2
3
4
5
6
7
8
9

import java.util.Scanner;
class Factorial
{
// this is a recursive function
int fact(int n)
{
int result;
if(n==1)

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

return 1;
result = fact(n-1) * n;
return result;

//From here function call it self (fact(n-1))

}
public class Recursion
{
public static void main(String args[])
{
int x;
Scanner s = new Scanner(System.in);
System.out.print("Enter int no = ");
x = s.nextInt();
Factorial f = new Factorial();
System.out.println("Factorial of" + x + " is " + f.fact(x));
}
}

Output :
Enter int no = 7
Factorial of7 is 5040
Here the method fact is recursive because it calls itself.
The whole precess something like this
result = fact(7-1) * 7 and so on until it returns 1.
So one thing is sure that we have to take care that in every recursive process there must be
a terminate condition to come out from recursion.
nested class :
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.
That means, if class B is defined within class A, then B is known to A, but not outside
A.
If A is nesting class B, then A has access to all the members of B, including private
members. But the B does not have access to the members of nested class.
There are two types of nested classes:
1.

Static

2.

Non Static

Static nested class


A static nested class is one which has the static modifier, as it is static it must access
the member of its enclosing class through an object.
That means it cannot refer to member of its enclosing class directly.
Non Static nested class
Non Static nested class is known as inner class.
It has access to all of its variables and methods of its outer class and can refer to
them directly.
An inner class is fully within the scope of its enclosing class.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

class Inner1
{
class Contents
{
private int i = 16;
public int value()
{
return i;
}
}
class Destination
{
private String label;
Destination(String whereTo)
{
label = whereTo;
}
}
public void ship(String dest)
{
Contents c = new Contents(); // create object of inner class Contents
Destination d = new Destination(dest); // create object of inner class Destination
System.out.println("Shipped " + c.value() + " item(s) to " + dest);
}

public static void main(String args[])


{
Inner1 p = new Inner1();
p.ship("Congo"); //call ship method of outer class "inner1"
}

Output

Shipped 16 item(s) to Congo


Let us see one more example but here the program will not compile
?
1
class Outer
2
{
3
int outer_x = 100;
4
void test()
5
{
6
Inner inner = new Inner();
7
inner.display();
8
}
9
10
// this is an inner class
11
12
class Inner
13
{
14
int y = 10; // y is local to Inner
15
void display()
16
{
17
System.out.println("display: outer_x = " + outer_x);
18
}
19
}
20
void showy()
21
{
22
System.out.println(y); // error, y not known here!
23
}
24 }
25
26 class InnerClassDemo
27 {
28
public static void main(String args[])
29
{
30
Outer outer = new Outer();
31
outer.test();
32
}
33 }
Here, y is declared as an instance variable of Inner. Thus it is not known outside of
that class and it cannot be used by showy( ).

Command Line Argument :


Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the programs name on
the command line when it is executed.
To access the command-line arguments inside a Java program is quite easythey are stored
as strings in the String array passed to main( ).
?
1
class CommandLine
2
{
3
public static void main(String args[])
4
{
5
for(int i=0; i < args.length; i++)
6
System.out.println("args[" + i + "]: " +args[i]);
7
}
8
}
Try executing this program, as shown here:
java CommandLine this is a test 100 -1
When you do, you will see the following output:
args[0]:
args[1]:
args[2]:
args[3]:
args[4]:
args[5]:

this
is
a
test
100
-1

But first of all you should have the basic knowledge about command line and how any java
program run through command prompt. CLICK HERE to know more.

Inheritance in java:
What is a Inheritance ?
The derivation of one class from another class is called Inheritance.
Type of inheritance :
A class that is inherited is called a superclass.
The class that does the inheriting is called as subclass.
In above figure all class A is superclass.
A subclass inherits all instance variables and methods from its superclass and also has its
own variables and methods.

One can inherit the class using keyword extends.


Syntax :
Class subclass-name extends superclass-name
{
// body of class.
}
In java, a class has only one super class.
Java does not support Multiple Inheritance.
One can create a hierarchy of inheritance in which a subclass becomes a superclass of
another subclass.
However, no class can be a superclass of itself.
EX :
?
1

class A

//superclass

int num1;

//member of superclass

int num2;

//member of superclass

void setVal(int no1, int no2)

num1 = no1;

num2 = no2;

9
10

}
}

11
12

class B extends A

//subclass B

//method of superclass

13

14

int multi;

15

void mul()

16

17

//method of subclass

multi = num1*num2;

18
19

//member of subclass

//accessing member of superclass from subclass

}
}

20
21

class inhe2

22

23

public static void main(String args[])

24

25

B subob = new B();

26

subob.setVal(5,6); //calling superclass method throgh subclass object

27

subob.mul();

28

System.out.println("Multiplication is " + subob.multi);

29
30

}
}

Output :

Multiplication is 30

Note : Private members of superclass is not accessible in subclass,


superclass is also called parentclass or baseclass,
subclass is also called childclass or derivedclass.

super - final - keywords in java:


Let us see now two most important keywords of java
1. super :
super keyword is used to call a superclass constructor and to call or access super class
members(instance variables or methods).
syntax of super :
=> super(arg-list)
When a subclass calls super() it is calling the constructor of its immediate superclass.
super() must always be the first statement executed inside a subclass constructor.
=> super.member
Here member can be either method or an instance variables.
This second form of super is most applicable to situation in which member names of a
subclass hide member of superclass due to same name.
EX :
?
1

class A1

public int i;

A1()

i=5;

7
8
9

}
}

10

class B1 extends A1

11

12

int i;

13

B1(int a,int b)

14

15

super();

16

//now we will change value of superclass variable i

17

super.i=a; //accessing superclass member from subclass

18

i=b;

19

20

void show()

21

//calling super class constructor

22

System.out.println("i in superclass = " + super.i );

23

System.out.println("i in subclass = " + i );

24
25

}
}

26
27

public class Usesuper

28

29

public static void main(String[] args)

30

31

B1 b = new B1(10,12);

32

b.show();

33
34
35

}
}

Output :

i in superclass = 10
i in subclass = 12

The instance variable i in B1 hides the i in A, super allows access to the i defined in the
superclass.

super can also be used to call methods that are hidden by a subclass.
2. final :
final keyword can be use with variables, methods and class.
=> final variables.
When we want to declare constant variable in java we use final keyword.
Syntax : final variable name = value;
=> final method
Syntax final methodname(arg)
When we put final keyword before method than it becomes final method.
To prevent overriding of method final keyword is used, means final method cant be override.
=> final class
A class that can not be sub classed is called a final class.
This is archived in java using the keyword final as follow.
Syntax : final class class_name {

...

Any attempt to inherit this class will cause an error and compiler will not allow it.
EX:

?
1

final class aa

final int a=10;

public final void ainc()

a++;

// The final field aa.a cannot be assigned

8
9

10
11

class bb extends aa

12

13

public void ainc()

14

15

//Cannot override the final method from aa

System.out.println("a = " + a);

16
17

// The type bb cannot subclass the final class aa

}
}

18
19

public class Final_Demo

20

21

public static void main(String[] args)

22

23

bb b1 = new bb();

24

b1.ainc();

25
26

}
}

Here no output will be there because all the comments in above program are errors.
Remove final keyword from class than you will get error like final method can not be
override.

Method overriding :
Defining a method in the subclass that has the same name, same arguments and same
return type as a method in the superclass and it hides the super class method is called
method overriding.
Now when the method is called, the method defined in the subclass is invoked and executed
instead of the one in the superclass.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class Xsuper
{
int y;
Xsuper(int y)
{
this.y=y;
}
void display()
{
System.out.println("super y = " +y);
}
}
class Xsub extends Xsuper
{
int z;
Xsub(int z , int y)
{
super(y);
this.z=z;
}
void display()
{
System.out.println("super y = " +y);
System.out.println("sub z = " +z);
}
}
public class TestOverride

30
31
32
33
34
35
36

public static void main(String[] args)


{
Xsub s1 = new Xsub(100,200);
s1.display();
}

Output :
super y = 200
sub z = 100
Here the method display() defined in the subclass is invoked.
Overloading VS Overriding :
Methodoverloading is comiple time polymorphism.
Method overriding is run time polymorphism.
Overloading a method is a way to provide more than one method in one class which have
same name but different argument to distinguish them.
Defining a method in the subclass that has the same name, same arguments and same
return type as a method in the superclass is called method overriding.
Multilevel Inheritance in java:
Multilevel Hierarchy :
?
1

class student

int rollno;

String name;

5
6

student(int r, String n)

rollno = r;

name = n;

10

11

void dispdatas()

12

13

System.out.println("Rollno = " + rollno);

14

System.out.println("Name = " + name);

15
16

}
}

17
18

class marks extends student

19

20

int total;

21

marks(int r, String n, int t)

22

23

super(r,n);

24

total = t;

//call super class (student) constructor

25

26

void dispdatam()

27

28

dispdatas();

29

System.out.println("Total = " + total);

30
31

// call dispdatap of student class

}
}

32
33

class percentage extends marks

34

35
36

int per;

37

percentage(int r, String n, int t, int p)

38

39

super(r,n,t); //call super class(marks) constructor

40

per = p;

41

42

void dispdatap()

43

44

dispdatam();

45

System.out.println("Percentage = " + per);

46

// call dispdatap of marks class

47

48

class Multi_Inhe

49

50

public static void main(String args[])

51

52

percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage

53

stu.dispdatap(); // call dispdatap of percentage class

54
55

}
}

Output :

Rollno = 1912
Name = SAM
Total = 350
Percentage = 50

It is common that a class is derived from another derived class.

The class student serves as a base class for the derived class marks, which in turn serves as
a base class for the derived class percentage.

The class marks is known as intermediated base class since it provides a link for the
inheritance between student and percentage.

The chain is known as inheritance path.

When this type of situation occurs, each subclass inherits all of the features found in all of
its super classes. In this case, percentage inherits all aspects of marks and student.
To understand the flow of program read all comments of program.
When a class hierarchy is created, in what order are the constructors for the
classes that
make up the hierarchy called?

EX :
?
1

class X

X()

System.out.println("Inside X's constructor.");

6
7
8

}
}

class Y extends X

10

11

Y()

12

13

System.out.println("Inside Y's constructor.");

14
15

// Create a subclass by extending class A.

}
}

16
17

class Z extends Y

18

19

Z()

20

21

System.out.println("Inside Z's constructor.");

22
23

// Create another subclass by extending B.

}
}

24
25

public class CallingCons

26

27

public static void main(String args[])

28

29

Z z = new Z();

30
31

}
}

Output:

Inside X's constructor.


Inside Y's constructor.
Inside Z's constructor.

The answer is that in a class hierarchy, constructors are called in order of derivation, from
superclass to subclass.

Further, since super( ) must be the first statement executed in a subclass constructor, this
order is the same whether or not super( ) is used.

If super( ) is not used, then the default or parameterless constructor of each superclass will
be executed.

As you can see from the output the constructors are called in order of derivation.

If you think about it, it makes sense that constructors are executed in order of derivation.

Because a superclass has no knowledge of any subclass, any initialization it needs to


perform is separate from and possibly prerequisite to any initialization performed by the
subclass. Therefore, it must be executed first.

Dynamic Method Dispatch:


Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
Dynamic method dispatch is important because this is how Java implements run-time
polymorphism.
method to execution based upon the type of the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
EX :

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

class A
{
void callme()
{
System.out.println("Inside A's callme method");
}
}
class B extends A
{
// override callme()
void callme()
{
System.out.println("Inside B's callme method");
}
}
class C extends A
{
// override callme()
void callme()
{
System.out.println("Inside C's callme method");
}
}
public class Dynamic_disp
{
public static void main(String args[])
{
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}

Output :
Inside A's callme method
Inside B's callme method
Inside C's callme method
Here reference of type A, called r, is declared.

The program then assigns a reference to each type of object to r and uses that reference
to invoke callme( ).
As the output shows, the version of callme( ) executed is determined by the type of object
being referred to at the time of the call.

Abstract Classes :
When the keyword abstract appears in a class definition, it means that zero or more of
its methods are abstract.
An abstract method has no body.
Some of the subclass has to override it and provide the implementation.
Objects cannot be created out of abstract class.
Abstract classes basically provide a guideline for the properties and methods of an
object.
In order to use abstract classes, they have to be subclassed.
There are situations in which you want to define a superclass that declares the structure
of a given abstraction without providing a complete implementation of every method.
That is, sometimes you want to create a superclass that only defines generalized form
that will be shared by all of its subclasses, leaving it to each subclass to fill in the details.
One way this situation can occur is when a superclass is unable to create a meaningful
implementation for a method.
Syntax :
abstract type name(parameter-list);
As you can see, no method body is present.
Any class that contains one or more abstract methods must also be declared abstract.
To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with the new operator.

Any subclass of an abstract class must either implement all of the abstract methods of
the superclass, or be itself declared abstract.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

abstract class A1
{
abstract void displayb1();
void displaya1()
{
System.out.println("This is a concrete method");
}
}
class B1 extends A1
{
void displayb1()
{
System.out.println("B1's implementation");
}
}
public class Abstract_Demo
{
public static void main(String args[])
{
B1 b = new B1();
b.displayb1();
b.displaya1();
}
}

Output :
B1's implementation
This is a concrete method
EX 2 :

?
1
2
3
4
5

abstract class shape


{
double dim1;
double dim2;
shape(double a, double b)

6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

dim1 = a;
dim2 = b;

}
abstract double area();

class rectangle extends shape


{
rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of rectangle.");
return dim1*dim2;
}
}
class triangle extends shape
{
triangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Area of triangle.");
return dim1*dim2/2;
}
}
public class Abstract_D2
{
public static void main(String args[])
{
rectangle r = new rectangle(10,20);
triangle t = new triangle(10,6);
System.out.println(r.area());
System.out.println(t.area());
}

Output:
Area of rectangle.
200.0
Area of triangle.
30.0

The Object class :


There is one special class, Object, defined by Java. All other classes are subclasses
of Object.
That is, Object is a superclass of all other classes.
This means that a reference variable of type Object can refer to an object of any other class.
Every class in java is descended from the java.lang.Object class.
If no inheritance is specified when a class is defined, the super class of the class is Object by
default.
EX :
public class circle { ... }
is equivalent to
public class circle extends Object { ... }
Methods of Object class

METHOD

PURPOSE

Object clone()

Creates a new object that is the same as the


object being cloned.

boolean equals(Object obj_name)

Determines whether one object is equal to


another

Void finalize()

Called before an unused object is recycled

Class getClass( )

Obtains the class of an object at run time.

int hashCode( )

Returns the hash code associated with the


invoking object.

void notify( )

Resumes execution of a thread waiting on the


invoking object.

void notifyAll( )

Resumes execution of all threads waiting on


the invoking object.

String toString( )

Returns a string that describes the object.

void wait( )
void wait(long milliseconds)

Waits on another thread of execution.

void wait(long milliseconds, int nanoseconds)

The methods getclass(), notify(), notifyall() and wait() are declared as final.
You may override the others.
tostring()
?public String tostring()
it returns a String that describe an object.
?It consisting class name, an at (@) sign and object memory address in hexadecimal.
EX :
Circle c1 = new Circle();
System.out.println(c1.tostring());
It will give O/P like Circle@15037e5
We can also write System.out.println(c1);
Polymorphism :
An object of a sub class can be used whenever its super class object is required.
This is commonly known as polymorphism.

In simple terms polymorphism means that a variable of super type can refer to a sub type
object.

Java Interface:
Interfaces are similar to abstract classes, but differ in their functionality.
In interfaces, none of the methods are implemented means interfaces defines methods
without body.
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body.
But, it can contain final variables, which must be initialized with values.
Once it is defined, any number of classes can implement an interface.
One class can implement any number of interfaces.
If we are implementing an interface in a class we must implement all the methods
defined in the interface as well as a class can also implement its own methods.

Interfaces add most of the functionality that is required for many applications which
would normally resort to using multiple inheritance in C++.

Defining interfaces in java with syntax:


Syntax :
[Access-specifier] interface interface-name
{
Access-specifier return-type method-name(parameter-list);
final type var1=value;
}
Where, Access-specifier is either public or it is not given.
When no access specifier is used, it results into default access specifier and if interface
has default access specifier then it is only available to other members of the same
package.
When it is declared as public, the interface can be used by any other code of other
package.
Interface-Name: name of an interface, it can be any valid identifier.
The methods which are declared having no bodies they end with a semicolon after the
parameter list. Actually they are abstract methods;
Any class that includes an interface must implement all of the methods. Variables can be
declared inside interface declarations.
They are implicitly final and static, means they can not be changed by implementing it in
a class.
They must also be initialized with a constant value.
EX :
interface Item
{
static final int code = 100;

static final String name = "Fan";


void display ( );
}

interface Area
{
static final float pi = 3.14F;
float compute ( float x, float y );
void show ( );
}

Once an interface has been defined, one or more classes can implement that interface.
To implement an interface, include the implements clause in a class definition, and then
create the methods declared by the interface.
The general form of a class that includes the implements clause looks like this:
Access-specifier
interface..]]

class

classname

[extends

superclass]

[implements

interface,

[,

{
// class body
}
If a class implements from more than one interface, names are separated by comma.
If a class implements two interfaces that declare the same method, then the same
method will be used by clients of either interface.
The methods that implement an interface must be declared as public.

The type-signature of implementing method must match exactly the type signature
specified in the interface.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

interface religion
{
String city = new String("Amritsar");
void greet();
void pray();
}
class gs implements religion
{
public void greet()
{
System.out.println("We greet - ABCD");
}
public void pray()
{
System.out.println("We pray at " + city + " XYZ ");
}
}
class iface1
{
public static void main(String args[])
{
gs sikh = new gs();
sikh.greet();
sikh.pray();
}
}

Output :
We greet - ABCD
We pray at Amritsar XYZ
EX 2 :
?
1
interface i1
2
{
3
void dispi1();
4
}
5
6
interface i2
7
{
8
void dispi2();
9
}
10
11 class c1 implements i1
12 {

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

public void dispi1()


{
System.out.println("This is display of i1");
}
}
class c2 implements i2
{
public void dispi2()
{
System.out.println("This is display of i2");
}
}
class c3 implements i1, i2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
class iface2
{
public static void main(String args[])
{
c1 c1obj = new c1();
c2 c2obj = new c2();
c3 c3obj = new c3();
c1obj.dispi1();
c2obj.dispi2();
c3obj.dispi1();
c3obj.dispi2();
}
}

Output :
This
This
This
This

is
is
is
is

display
display
display
display

of
of
of
of

i1
i2
i1
i2

EX 3 : // Implementing interface having common function name


?
1
interface i1

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

void disp();

}
interface i2
{
void disp();
}
class c implements i1, i2
{
public void disp()
{
System.out.println("This is display .. ");
}
}
class iface7
{
public static void main(String args[])
{
c cobj = new c();
cobj.disp();
}

Output :
This is display ..
Note : When implementing an interface method, it must be declared as public. It is possible
for classes that implement interfaces to define additional members of their own.
Partial Implementation of Interface :
If we want to implement an interface in a class we have to implement all the methods
defined in the interface.
But if a class implements an interface but does not fully implement the method defined
by that interface, then that class must be declared as abstract.
EX :
?
1
2
3
4
5
6

interface i1
{
void disp1();
void disp2();
}

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

abstract class c1 implements i1


{
public void disp1()
{
System.out.println("This is display of 1");
}
}
class c2 extends c1
{
public void disp2()
{
System.out.println("This is display of 2");
}
}
class iface
{
public static void main(String args[])
{
c2 c2obj = new c2();
c2obj.disp1();
c2obj.disp2();
}
}

Output :
This is display of 1
This is display of 2

Accessing interface variable :


One can declare variable as object references that uses an interface rather than a class
type.
When you call a method through one of these references, the correct version will be called
based on the actual instance of the interface being referred to.
?
1
2
3
4
5
6
7
8
9

interface AreaCal
{
final double pi = 3.14;
double areacalculation(double r);
}
class Circle implements AreaCal
{
public double areacalculation(double r)

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

double ar;
ar = pi*r*r;
return ar;

class iface3
{
public static void main(String args[])
{
double area;
AreaCal ac = new Circle();
area = ac.areacalculation(10.25);
System.out.println("Area of Circle is : " + area);
}
}

Output :
Area of Circle is : 329.89625

Here variable ac is declared to be of the interface type AreaCal,


it was assigned an instance of circle. Although ac can be used to access the
areacalculation() method,
it cannot access any other members of the client class. An interface reference variable only
has knowledge of the method declared by its interface declaration.
Extending interfaces :
One interface can inherit another by use of the keyword extends. The syntax is the same as
for inheriting classes.
When a class implements an interface that inherits another interface,
It must provide implementation of all methods defined within the interface inheritance.
Note : Any class that implements an interface must implement all methods defined by that
interface, including any that inherited from other interfaces.
EX :
?
1
2
3
4

interface if1
{
void dispi1();
}

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

interface if2 extends if1


{
void dispi2();
}
class cls1 implements if2
{
public void dispi1()
{
System.out.println("This is display of i1");
}
public void dispi2()
{
System.out.println("This is display of i2");
}
}
public class Ext_iface
{
public static void main(String args[])
{
cls1 c1obj = new cls1();

c1obj.dispi1();
c1obj.dispi2();

Output :
This is display of i1
This is display of i2
Note : We have to define disp1() and disp2() in cls1.
Multiple inheritance using interface..
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14

class stu
{
int rollno;
String name = new String();
int marks;
stu(int r, String n, int m)
{
rollno = r;
name = n;
marks = m;
}
}
interface i

15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

void display();

}
class studerived extends stu implements i
{
studerived(int r, String n, int m)
{
super(r,n,m);
}
public void display()
{
System.out.println("Displaying student details .. ");
System.out.println("Rollno = " + rollno);
System.out.println("Name = " + name);
System.out.println("Marks = " + marks);
}
}
public class Multi_inhe_demo
{
public static void main(String args[])
{
studerived obj = new studerived(1912, "Ram", 75);
obj.display();
}
}

Output :
Displaying student details ..
Rollno = 1912
Name = Ram
Marks = 75
We can make various forms of interface implementation as below

String Handling in java:


In Java, a string is defined as a sequence of characters.
But, unlike many other languages that implement strings as character arrays, java
implements strings as objects of type String.
Java handles String by two classes StringBuffer and String. The String and StringBuffer
classes are defined in java.lang.
Thus, they are available to all programs automatically.
1. String Concatenation (+)
EX :
?
1

import java.util.*;

class str3

public static void main(String args[])

String s1 = new String ("Java");

String s2 = "2all";

String s3 = s1+s2;

System.out.println("S1 = " + s1);

10

System.out.println("S2 = " + s2);

11

System.out.println("Concatenation Operator = " + s1+s2);

12

System.out.println("S3 = " + s3);

13
14

byte num [] = {65,66,67,68};

15

String s4 = new String(num);

16

System.out.println("S4 = " + s4);

17
18

}
}

Output :

S1 = Java
S2 = 2all
Concatenation Operator = Java2all
S3 = Java2all
S4 = ABCD

2. Character Extraction :

The String class provides ways in which characters can be extracted from a String object.

3. String Comparison :
The String class provides several methods that compare strings or substrings within strings.
equals( ) used to compare two strings
General form:
Boolean equals(Object str)
Here, str is a String object.
It returns true if the strings contain the same character otherwise it returns false.
The comparison is case-sensitive.
equalsIgnoreCase( ) Same as equals but this ignores case.
General form:
Boolean equalsIgnoreCase(String str)
Here, str is the String object.
It returns true if the strings contain the same character otherwise it returns false.
This is case in sensitive.
regionMatches( )
This method compares a specific region inside a string with another specific region in
another string.
There is an overloaded form that allows you to ignore case in such comparisons.
General form:

Boolean regionMatches(int startIndex, String str2, int str2StartIndes, int numChars)


Boolean regionMatches(Boolean
str2StartIndex, int numChars)

ignoreCase,

int

startIndex,

String

str2,

int

startsWith( ) and endsWith()


The startsWith( ) method determines whether a given String begins with a specified
string.
endsWith( ) determines whether the String ends with a specified string.
General Form
Boolean startsWith(String str)
Boolean endsWith(String str)
equals( ) Versus = =
Equals( ) method and the = = operator perform two different operations. The equals ( )
method compares the characters inside a String object. The = = operator compares two
object references to see whether they refer to the same instance.
compareTo( )
It is not enough to know that two strings just for equal or not. For sorting applications, we
need to know which is less than, equal to, or greater than the other string.
The String method compareTo( ) serves this purpose.
General Form:
int compareTo(String str)
4 Modifying a string :
If we want to modify a String, we must either copy it into a StringBufer or we can use
following String methods:
5 valueOf() :
The valueOf() method converts data from internal format into a human-readable form. It
has several forms:
String valueOf(double num)

String valueOf(long num)


String valueOf(Object ob)
String valueOf(char chars[ ] )
String valueOf(char chars[], int startIndex, int numChars)

String Methods in java:


Example :
?
1

import java.util.*;

class str1

public static void main(String args[])

String s1 = "Bhagirath";

System.out.println("S1 = " + s1);

int length = s1.length();

System.out.println("S1 lenth = " + length);

10

System.out.println("S1 lowercase = " + s1.toLowerCase());

11

System.out.println("S1 uppercase = " + s1.toUpperCase());

12

System.out.println("S1 replace a with z = " + s1.replace('a','z'));

13

System.out.println("S1 indexOf('e')= " + s1.indexOf('e'));

14

System.out.println("S1 lastindexof('e') = " + s1.lastIndexOf('e'));

15

String s2 = "ViewSonic";

16

System.out.println("S2 = " + s2);

17

System.out.println("S1 and S2 trim = " + s1.trim() + s2.trim());

18

System.out.println("S1 and S2 equals = " + s1.equals(s2));

19

System.out.println("S1 and S2 equals ignoring case = " + s1.equalsIgnoreCase(s2));

20

System.out.println("S1 and S2 compareTo = " + s1.compareTo(s2));

21

System.out.println("S1 and S2 concate = " + s1.concat(s2));

22

System.out.println("S1 substring(n) = " + s1.substring(5));

23

System.out.println("S1 substring(n,m) = " + s1.substring(5,8));

24

System.out.println("S1 toString() = " + s1.toString());

25

int i = 100;

26

System.out.println("S1.valueOf(variable) = " + (s1.valueOf(i)).length()); // converts the parame

27

System.out.println("Start with " + s1.startsWith("P"));

28

System.out.println("Start with " + s1.endsWith("y"));

29
30
31

}
}

Output :

S1 = Bhagirath
S1 lenth = 9
S1 lowercase = bhagirath
S1 uppercase = BHAGIRATH
S1 replace a with z = Bhzgirzth
S1 indexOf('e')= -1
S1 lastindexof('e') = -1
S2 = ViewSonic
S1 and S2 trim = BhagirathViewSonic
S1 and S2 equals = false
S1 and S2 equals ignoring case = false

S1 and S2 compareTo = -20


S1 and S2 concate = BhagirathViewSonic
S1 substring(n) = rath
S1 substring(n,m) = rat
S1 toString() = Bhagirath
S1.valueOf(variable) = 3
Start with false
Start with false
?
1

import java.util.*;

class str4

public static void main(String args[])

String s = "This is a dAmo of the getChars method.";

int start = 10;

int end = 14;

char buf[] = new char[10];

10

//System.out.println("Character at 10 = " + s.charAt(10));

11

s.getChars(start, end, buf,0);

12

System.out.println(buf);

13

s.getChars(start, end, buf,5);

14

System.out.println(buf);

15
16

byte bt [] = new byte[10];

17

s.getBytes(start, end, bt,0);

18

System.out.println(bt[0]);

19

System.out.println(bt[1]);

20

System.out.println(bt[2]);

21

System.out.println(bt[3]);

22
23

char buf1[] = s.toCharArray();

24

System.out.println(buf1);

25
26
27

}
}

Output :

jav
jav jav
32
74
97
118
Welcome to Java2all

?
1

import java.util.*;

class str5

public static void main(String args[])

String s1 = "Rome was not built in a not day";

System.out.println("S1 = " + s1);

/*System.out.println("S1 = " + s1.indexOf('o'));

System.out.println("S1 = " + s1.indexOf("not"));

10

System.out.println("S1 = " + s1.indexOf('o',5));

11

System.out.println("S1 = " + s1.indexOf("not", 15));

12
13

System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o'));

14

System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not"));

15

System.out.println("S1 lastIndexOf= " + s1.lastIndexOf('o',15));

16

System.out.println("S1 lastIndexOf= " + s1.lastIndexOf("not", 15));

17

*/

18

String s2 = "Rome was not built in a Not day";

19

System.out.println("S2 = " + s2);

20

//System.out.println("S1 = " + s1.indexOf("not"));

21

//System.out.println("S1 = " + s1.lastIndexOf("not"));

22

System.out.println("Region Matches = ");

23

boolean b1 = s1.regionMatches(false,9,s2,24,3);

24

System.out.println("b1 = " + b1);

25
26
27
28

}
}

Output :

S1 = Rome was not built in a not day


S2 = Rome was not built in a Not day
Region Matches =
b1 = false

?
1

import java.util.*;

class str6

public static void main(String args[])

String s1 = "Hello";

String s2 = new String(s1);

System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));

System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));

10
11
12
13

}
}

Output :

Hello equals Hello -> true


Hello == Hello -> false

StringBuffer class :

StringBuffer is a peer class of String. String creates strings of fixed length, while
StringBuffer creates strings of flexible length that can be modified in terms of both
length and content.
So Strings that need modification are handled by StringBuffer class.
We can insert characters and substrings in the middle of a string, or append another
string to the end.
StringBufer defines these Constructor:
StringBuffer()
StringBuffer(int size)
StringBuffer(String str)

Method Call

Task Performed

Sb.length()

Gives the current length of a StringBuffer.

Sb.capacity()

Gives the total allocated capacity (default 16)

setLength(int len)

Set the length of the buffer within a String


Buffer object.

charAt(int where)

Gives the value of character

setCharAt(int where, char ch)

Set the value of a character within a


StringBuffer.

S1.append(s2)

Appends the string s2 to s1 at the end

S1.insert(n,s2)

Inserts the string s2 at the position n of the


string s1

S1.reverse()

Reverse the string of s1

S1.deleteCharAt(nth)

Delete the nth character of string s1

S1.delete(StartIndex, endIndex)

Delete characters from start to end.

EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

import java.util.*;
class strbuf1
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer();
StringBuffer s2 = new StringBuffer("Bhagirath");
StringBuffer s3 = new StringBuffer(s2);
StringBuffer s4 = new StringBuffer(100);
System.out.println("s1 = " + s1);
System.out.println("s2 = " + s2);
System.out.println("s3 = " + s3);
System.out.println("s1.length
System.out.println("s2.length
System.out.println("s3.length
System.out.println("s4.length

=
=
=
=

"
"
"
"

+
+
+
+

s1.length());
s2.length());
s3.length());
s4.length());

System.out.println("s1.capacity
System.out.println("s2.capacity
System.out.println("s3.capacity
System.out.println("s4.capacity

=
=
=
=

"
"
"
"

+
+
+
+

}
}

Output :
s1 =
s2 = Bhagirath
s3 = Bhagirath
s1.length = 0
s2.length = 9
s3.length = 9
s4.length = 0
s1.capacity = 16
s2.capacity = 25
s3.capacity = 25

s1.capacity());
s2.capacity());
s3.capacity());
s4.capacity());

s4.capacity = 100
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import java.util.*;
class strbuf2
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Java2all");
StringBuffer s2 = new StringBuffer("Hello");
System.out.println("s1 = " + s1);
//System.out.println("s1.charAt(5) = " + s1.charAt(5));
//s1.setCharAt(5,'z');
//System.out.println("s1 = " + s1);
//System.out.println("Inserting String = " + s1.insert(5,s2));
//System.out.println("s1 = " + s1);
//System.out.println("Appending String = " + s1.append(s2));
//System.out.println("s1 = " + s1);
//System.out.println("Reversing String = " + s1.reverse());
//System.out.println("Deleting 5th character = " + s1.deleteCharAt(5));
System.out.println("Deleting 5 to 8 character = " + s1.delete(5,8));
}
}

Output :
s1 = Java2all
Deleting 5 to 8 character = Java2
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import java.util.*;
public class strbuf3
{
public static void main(String[] args)
{
StringBuffer s = new StringBuffer("Hello world!");
System.out.println("s = " + s);
System.out.println("s.length() = " + s.length());
System.out.println("s.length() = " + s.capacity());
// Change the length of buffer to 5 characters:
s.setLength(5);
System.out.println(s);
System.out.println("s.length() = " + s.length());

18
19
20
21

System.out.println("s.length() = " + s.capacity());


}

Output :
s = Hello world!
s.length() = 12
s.length() = 28
Hello
s.length() = 5
s.length() = 28

Introduction to JDBC:
JDBC - Java Database Connectivity.
JDBC provides API or Protocol to interact with different databases.
With the help of JDBC driver we can connect with different types of databases.
Driver is must needed for connection establishment with any database.
A driver works as an interface between the client and a database server.

JDBC have so many classes and interfaces that allow a java application to send request
made by user to any specific DBMS(Data Base Management System).
JDBC supports a wide level of portability.
JDBC provides interfaces that are compatible with java application

components and specification of JDBC:


Components of JDBC:
JDBC has four main components as under and with the help of these components java
application can connect with database.
The JDBC API - it provides various methods and interfaces for easy communication with
database.
The JDBC DriverManager - it loads database specific drivers in an application to establish
connection with database.
The JDBC test suite - it will be used to test an operation being performed by JDBC drivers.
The JDBC-ODBC bridge - it connects database drivers to the database.
JDBC Specification:
Different version of JDBC has different specification as under.
JDBC 1.0 - it provides basic functionality of JDBC
JDBC 2.0 - it provides JDBC API(JDBC 2.0 Core API and JDBC 2.0 Optional Package API).
JDBC 3.0 - it provides classes and interfaces in two packages(java.sql and javax.sql).
JDBC 4.0 - it provides so many extra features like
Auto loading of the driver interface.
Connection management
ROWID data type support.
Enhanced support for large object like BLOB(Binary Large Object) and CLOB(Character
Large Object).

JDBC Architecture:
As we all know now that driver is required to communicate with database.
JDBC API provides classes and interfaces to handle request made by user and response
made by database.
Some of the important JDBC API are as under.

DriverManager
Driver
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
DatabaseMetaData
ResultSetMetaData
Here The DriverManager plays an important role in JDBC architecture.
It uses some database specific drivers to communicate our J2EE application to database.

As per the diagram first of all we have to program our application with JDBC API.
With the help of DriverManager class than we connect to a specific database with the help of
spcific database driver.
Java drivers require some library to communicate with the database.
We have four different types of java drivers.
We will learn all that four drivers with architecture in next chapter.
Some drivers are pure java drivers and some are partial.
So with this kind of JDBC architecture we can communicate with specific database.
We will learen programatically all this thing in further chapter.

JDBC Driver Types:


There are four categories of drivers by which developer can apply a connection between
Client (The JAVA application or an applet) to a DBMS.
(1)

Type 1 Driver : JDBC-ODBC Bridge.

(2)

Type 2 Driver : Native-API Driver (Partly Java driver).

(3)

Type 3 Driver : Network-Protocol Driver (Pure Java driver for database Middleware).

(4)
Type 4 Driver : Native-Protocol Driver (Pure Java driver directly connected to
database).

(1) Type 1 Driver: JDBC-ODBC Bridge :The JDBC type 1 driver which is also known as a JDBC-ODBC Bridge is a convert JDBC
methods into ODBC function calls.
Sun provides a JDBC-ODBC Bridge driver by sun.jdbc.odbc.JdbcOdbcDriver.
The driver is a platform dependent because it uses ODBC which is depends on native
libraries of the operating system and also the driver needs other installation for example,
ODBC must be installed on the computer and the database must support ODBC driver.
Type 1 is the simplest compare to all other driver but its a platform specific i.e. only on
Microsoft platform.
The JDBC-ODBC Bridge is use only when there is no PURE-JAVA driver available for a
particular database.
Architecture Diagram:

Process:
Java Application JDBC APIs
JDBC Driver Manager
Driver Database library APIs Database

Type 1 Driver

ODBC

Advantage:
(1)

Connect to almost any database on any system, for which ODBC driver is installed.

(2) Its an easy for installation as well as easy(simplest) to use as compare the all other
driver.
Disadvantage:
(1)

The ODBC Driver needs to be installed on the client machine.

(2) Its a not a purely platform independent because its use ODBC which is depends on
native libraries of the operating system on client machine.
(3) Not suitable for applets because the ODBC driver needs to be installed on the client
machine.

(2) Type 2 Driver: Native-API Driver (Partly Java driver) :The JDBC type 2 driver is uses the libraries of the database which is available at client side
and this driver converts the JDBC method calls into native calls of the database so this
driver is also known as a Native-API driver.
Architecture Diagram :

Process:
Java Application JDBC APIs
JDBC Driver Manager
Client Database library APIs Database

Type 2 Driver

Vendor

Advantage:
(1) There is no implantation of JDBC-ODBC Bridge so its faster than a type 1 driver; hence
the performance is better as compare the type 1 driver (JDBC-ODBC Bridge).
Disadvantage:
(1) On the client machine require the extra installation because this driver uses the vendor
client libraries.
(2) The Client side software needed so cannot use such type of driver in the web-based
application.
(3)

Not all databases have the client side library.

(4)

This driver supports all JAVA applications except applets.

(3) Type 3 Driver: Network-Protocol Driver (Pure Java driver for database
Middleware) :The JDBC type 3 driver uses the middle tier(application server) between the calling program
and the database and this middle tier converts JDBC method calls into the vendor specific

database protocol and the same driver can be used for multiple databases also so its also
known as a Network-Protocol driver as well as a JAVA driver for database middleware.
Architecture Diagram:

Process:
Java Application
JDBC APIs
Middleware (Server) any Database

JDBC Driver Manager

Type 3 Driver

Advantage:
(1) There is no need for the vendor database library on the client machine because the
middleware is database independent and it communicates with client.
(2) Type 3 driver can be used in any web application as well as on internet also because
there is no any software require at client side.
(3) A single driver can handle any database at client side so there is no need a separate
driver for each database.
(4) The middleware server can also provide the typical services such as connections,
auditing, load balancing, logging etc.
Disadvantage:
(1) An Extra layer added, may be time consuming.
(2) At the middleware develop the database specific coding, may be increase complexity.

(4) Type 4 Driver: Native-Protocol Driver (Pure Java driver directly connected to
database) :The JDBC type 4 driver converts JDBC method calls directly into the vendor specific
database protocol and in between do not need to be converted any other formatted system
so this is the fastest way to communicate quires to DBMS and it is completely written in
JAVA because of that this is also known as the direct to database Pure JAVA driver.
Architecture Diagram:

Process:
Java Application JDBC APIs
Driver) Database Server

JDBC Driver Manager

Type 4 Driver (Pure JAVA

Advantage:
(1)

Its a 100% pure JAVA Driver so its a platform independence.

(2)

No translation or middleware layers are used so consider as a faster than other drivers.

(3) The all process of the application-to-database connection can manage by JVM so the
debugging is also managed easily.
Disadvantage:
(1)There is a separate driver needed for each database at the client side.
(2) Drivers are Database dependent, as different database vendors use different network
protocols.

JDBC APIs:
If any java application or an applet wants to connect with a database then there are various
classes and interfaces available in java.sql package.
Depending on the requirements these classes and interfaces can be used.
Some of them are list out the below which are used to perform the various tasks with
database as well as for connection.
Class or Interface

Description

Java.sql.Connection

Create a connection with specific database

Java.sql.DriverManager

The task of DriverManager is to manage the database


driver

Java.sql.Statement

It executes SQL statements for particular connection and


retrieve the results

Java.sql.PreparedStatement

It allows the programmer to create prepared SQL


statements

Java.sql.CallableStatement

It executes stored procedures

Java.sql.ResultSet

This interface provides methods to get result row by row


generated by SELECT statements

Now we are going to elobrate each class or interface in detail with their methods and will
give program for each one in next topic.

The Connection interface:


The Connection interface used to connect java application with particular database.
After crating the connection with database we can execute SQL statements for that
particular connection using object of Connection and retrieve the results.
The interface has few methods that makes changes to the database temporary or
permanently.
The some methods are as given below.
Method

Description

void close()

This method frees an object of type


Connection from database and other JDBC
resources.

void commit()

This method makes all the changes made


since the last commit or rollback permanent. It
throws SQLExeception.

Statement createStatement()

This method creates an object of type


Statement for sending SQL statements to the
database. It throws SQLExeception.

boolean isClosed()

Return true if the connection is close else


return false.

CallableStatement prepareCall(String s)

This method creates an object of type


CallableStatement for calling the stored
procedures from database. It throws
SQLExeception.

PreparedStatement prepareStatement(String
s)

This method creates an object of type


PrepareStatement for sending dynamic (with
or without IN parameter) SQL statements to
the database. It throws SQLExeception.

void rollback()

This method undoes all changes made to the


database.

The example program for Connection interface and its methods are given in next chapter for
different databases.

Statement Interface:
The Statement interface is used for to execute a static query.
Its a very simple and easy so it also calls a Simple Statement.
The statement interface has several methods for execute the SQL statements and also get
the appropriate result as per the query sent to the database.
Some of the most common methods are as given below
Method

Description

void close()

This method frees an object of type Statement from


database and other JDBC resources.

boolean execute(String s)

This method executes the SQL statement specified by s.


The getResultSet() method is used to retrieve the result.

ResultSet getResultet()

This method retrieves the ResultSet that is generated by


the execute() method.

ResultSet executeQuery(String s)

This method is used to execute the SQL statement


specified by s and returns the object of type ResultSet.

int getMaxRows()

This method returns the maximum number of rows


those are generated by the executeQuery() method.

Int executeUpdate(String s)

This method executes the SQL statement specified by s.


The SQL statement may be a SQL insert, update and
delete statement.

The example program for Statement interface and its methods are given in next chapter for
different databases.
The Prepared Statement Interface:
The Prepared Statement interface is used to execute a dynamic query (parameterized SQL
statement) with IN parameter.
IN Parameter:In some situation where we need to pass different values to an query then such values can
be specified as a ? in the query and the actual values can be passed using the setXXX()
method at the time of execution.

Syntax :
setXXX(integer data ,XXX value);
Where XXX means a data type as per the value we want to pass in the query.
For example,
String query = "Select * from Data where ID = ? and Name = ? ";
PreparedStatement ps = con.prepareStatement(query);
ps.setInt(1, 1);
ps.setString(2, "Ashutosh Abhangi");
The Prepared statement interface has several methods to execute the parameterized SQL
statements and retrieve appropriate result as per the query sent to the database.
Some of the most common methods are as given below
Method

Description

void close()

This method frees an object of type Prepared


Statement from database and other JDBC
resources.

boolean execute()

This method executes the dynamic query in the


object of type Prepared Statement.The
getResult() method is used to retrieve the
result.

ResultSet executeQuery()

This method is used to execute the dynamic


query in the object of type Prepared
Statement and returns the object of type
ResultSet.

Int executeUpdate()

This method executes the SQL statement in


the object of type Prepared Statement. The
SQL statement may be a SQL insert, update
and delete statement.

ResultSetMetaData getMetaData()

The ResultSetMetaData means a deta about


the data of ResultSet.This method retrieves an
object of type ResultSetMetaData that contains
information about the columns of the ResultSet
object that will be return when a query is
execute.

int getMaxRows()

This method returns the maximum number of

rows those are generated by the


executeQuery() method.
The example program for Prepared Statement interface and its methods are given in next
chapter for different databases.

Você também pode gostar