Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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.
class Box
double width;
double height;
double depth;
class BoxDemo2
9
10
11
12
13
double vol;
14
15
mybox1.width = 10;
16
mybox1.height = 20;
17
mybox1.depth = 15;
18
19
mybox2.width = 3;
20
mybox2.height = 6;
21
mybox2.depth = 9;
22
23
24
25
26
27
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
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
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
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:
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
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
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.
2.
3.
One can also declare a static block which gets executed exactly once, when the class is first
loaded.
EX :
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
o A private variable can be used by methods in its own class but not by objects
of any other class.
o
o The only place these variables and methods can be seen is from within their
own class.
protected:
o
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
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
Access
Public
Protected
Default
Private
Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
No
No
No
Yes
Yes
Yes
No
Yes
Yes
Yes
No
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
int n1;
int n2;
MethodOver()
n1 = 10;
n2 = 20;
10
void square()
11
12
13
14
15
16
n1 = p1;
17
18
19
20
21
n1 = p1;
22
n2 = p2;
23
24
25
26
27
28
29
obj1.square(4);
30
31
32
}
}
Output :
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
30
31
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
50
51
52
53
54
55
56
57
58
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 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;
}
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;
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
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
Output :
a
a
b
a
a
b
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
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
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;
}
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
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);
}
Output
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.
class A
//superclass
int num1;
//member of superclass
int num2;
//member of superclass
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
}
}
20
21
class inhe2
22
23
24
25
26
27
subob.mul();
28
29
30
}
}
Output :
Multiplication is 30
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
17
18
i=b;
19
20
void show()
21
22
23
24
25
}
}
26
27
28
29
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
a++;
8
9
10
11
class bb extends aa
12
13
14
15
16
17
}
}
18
19
20
21
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
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
14
15
16
}
}
17
18
19
20
int total;
21
22
23
super(r,n);
24
total = t;
25
26
void dispdatam()
27
28
dispdatas();
29
30
31
}
}
32
33
34
35
36
int per;
37
38
39
40
per = p;
41
42
void dispdatap()
43
44
dispdatam();
45
46
47
48
class Multi_Inhe
49
50
51
52
percentage stu = new percentage(1912, "SAM", 350, 50); //call constructor percentage
53
54
55
}
}
Output :
Rollno = 1912
Name = SAM
Total = 350
Percentage = 50
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.
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()
6
7
8
}
}
class Y extends X
10
11
Y()
12
13
14
15
}
}
16
17
class Z extends Y
18
19
Z()
20
21
22
23
}
}
24
25
26
27
28
29
Z z = new Z();
30
31
}
}
Output:
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.
?
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
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();
Output:
Area of rectangle.
200.0
Area of triangle.
30.0
METHOD
PURPOSE
Object clone()
Void finalize()
Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
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++.
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
Output :
This
This
This
This
is
is
is
is
display
display
display
display
of
of
of
of
i1
i2
i1
i2
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
Output :
This is display of 1
This is display of 2
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
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
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
import java.util.*;
class str3
String s2 = "2all";
String s3 = s1+s2;
10
11
12
13
14
15
16
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:
ignoreCase,
int
startIndex,
String
str2,
int
import java.util.*;
class str1
String s1 = "Bhagirath";
10
11
12
13
14
15
String s2 = "ViewSonic";
16
17
18
19
20
21
22
23
24
25
int i = 100;
26
27
28
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
import java.util.*;
class str4
10
11
12
System.out.println(buf);
13
14
System.out.println(buf);
15
16
17
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
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
10
11
12
13
14
15
16
17
*/
18
19
20
21
22
23
boolean b1 = s1.regionMatches(false,9,s2,24,3);
24
25
26
27
28
}
}
Output :
?
1
import java.util.*;
class str6
String s1 = "Hello";
10
11
12
13
}
}
Output :
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()
Sb.capacity()
setLength(int len)
charAt(int where)
S1.append(s2)
S1.insert(n,s2)
S1.reverse()
S1.deleteCharAt(nth)
S1.delete(StartIndex, endIndex)
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
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
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.
(2)
(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)
(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)
(4)
(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
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
Advantage:
(1)
(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
Java.sql.DriverManager
Java.sql.Statement
Java.sql.PreparedStatement
Java.sql.CallableStatement
Java.sql.ResultSet
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.
Description
void close()
void commit()
Statement createStatement()
boolean isClosed()
CallableStatement prepareCall(String s)
PreparedStatement prepareStatement(String
s)
void rollback()
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()
boolean execute(String s)
ResultSet getResultet()
ResultSet executeQuery(String s)
int getMaxRows()
Int executeUpdate(String s)
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()
boolean execute()
ResultSet executeQuery()
Int executeUpdate()
ResultSetMetaData getMetaData()
int getMaxRows()