OOP Using JAVA Unit-II
OOP Using JAVA Unit-II
UNIT-II
Arrays, Command Line Arguments, Strings-String Class Methods
Classes & Objects: Creating Classes, declaring objects, Methods, parameter
passing, static fields and methods, Constructors, and ‘this’ keyword, overloading
methods and access
Inheritance: Inheritance hierarchies, super and subclasses, member access rules,
‘super’ keyword, preventing inheritance: final classes and methods, the object class
and its methods;
Polymorphism: Dynamic binding, method overriding, abstract classes and
methods;
Arrays
Definition
• An array is a collection of same type variables referenced by a common
name.
• All the elements in the array are of the same data type.
• Elements of an array are accessed individually using the index.
• The index value in every array starts with 0 (zero).
• An array can have one or more dimensions
One Dimensional Array
A list of items can be given one variable name using only one subscript
and such a variable is called a single-dimensional variable or a one-dimensional
array.
Creating an array
Creation of arrays is a two step process:
1) Declaring an array variable.
2) Allocating memory for the array.
Declaration of arrays
Syntax for declaring an array variable is:
type array-name[];
Here, type – Data type of the array and array-name is any valid identifier.
We can also declare an array in java as follows,
Type[] array-name;
Examples: int number[];
1
OOP using JAVA
float average[];
int[] counter;
Creation of arrays (Allocating the memory for an array)
After declaring an array, we need to create it in memory. Java allows us to
create arrays using new operator only.
Syntax for allocating memory for an array:
array-name = new type[size];
Here, new – keyword used to allocate memory for the array, and
size – No of elements that the array will hold.
We can combine both the steps into a single one as shown below:
type array-name[] = new type[size];
Examples:
number=new int[5];
average=new float[10];
The following figure illustrates the creation of an array in memory.
Initialization of Arrays
Every array element is accessed using its index value.
Syntax for initializing the array elements is:
array-name[index] = value;
Example:
int a[] = new int[3];
a[0] = 10;
2
OOP using JAVA
a[1] = 20;
a[2] = 30;
There is another way for initializing array elements, right at the time of
declaring the array.
Example:
int a[] = {1,2,3,4,5};
In the above example, ‘a’ is an integer type array with size automatically
set to 5. All the 5 elements are initialized with the values 1,2,3,4,5.
a[0] is 1, a[1] is 2, a[2] is 3, a[3] is 4 and a[4] is 5.
Array Length
In java, all arrays store the allocated size in a variable named length. We
can obtain the length of the array using the length.
Example:
int number[]={10,20,30,40,50};
int n=number.length;
The following java program illustrates the concept of single dimensional arrays.
Aim: To sort an array of elements
Program:
//ArrayDemo.java
import java.io.*;
class ArrayDemo
{
public static void main(String[] args) throws IOException
{
int a[];
int n,temp;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter the array size.....");
n=Integer.parseInt(in.readLine());
a=new int[n];
System.out.println("Enter the elements into the array");
for(int i=0;i<n;i++)
3
OOP using JAVA
{
a[i]=Integer.parseInt(in.readLine());
}
System.out.println("The array elements before Sorting are....");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
System.out.println("The array elements after Sorting are.....");
{
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>=a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
4
OOP using JAVA
Output
Two-Dimensional Arrays
Until now we have only seen one-dimensional array. But, an array in
general can have more than one dimension.
Let’s see about two-dimensional arrays. For each dimension, we must
specify an extra set of [].
A two dimensional array is declared as shown below:
int a[][] = new int[3][4];
‘a’ is a two dimensional array which can hold 12 elements in 3 rows
and 4 columns.
Initializing two dimensional array elements is done using the index values:
int a[][] = new int[2][2];
a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
The following is a representation of a two-dimensional array in memory.
5
OOP using JAVA
{
for(int j=0;j<n;j++)
{
System.out.print(" " + a[i][j]);
}
System.out.println("\n");
}
}//main()
}//ArrayDemo1
Output
7
OOP using JAVA
****************************************************************
Command Line Arguments
In java command-line argument is an argument i.e. passed at the time of
running the java program.
The arguments passed from the console can be received in the java program
and it can be used as an input. So, it provides a convenient way to check the
behaviour of the program for the different values. We can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.
Example:
class Commandline
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("No.of Arguments="+count);
while(i<count)
{
str=args[i];
i=i+1;
System.out.println(i+":"+"Java is "+str);
}
}
}
Output:
****************************************************************
Strings
• A string is a sequence/group of characters.
• Strings in java are implemented as objects of the class “String” unlike other
languages which implement strings using character arrays.
• Once a string (object) is created, we cannot change the characters in that
string. Rather, we can create a new string object.
8
OOP using JAVA
String Arrays:
We can also create and use arrays that contain strings. The statement,
String names[]=new String[3];
will create an names array of size 3 to hold three string constants
9
OOP using JAVA
for(int i=0;i<size;i++)
System.out.println(names[i]);
}
}
Output:
StringBuffer Class :
StringBuffer is a peer class of String. While String creates string of fixed
length, StringBuffer creates strings of flexible length that can be modified in
terms of both length and content. We can insert characters and substrings in the
middle of a string, or append another string to the end. Below, there are some of
methods that are frequently used in string manipulations.
Method Task
s1.setCharAt(n,‘x‘) Modifies the nth character to x
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.setLength(n) Sets the length of the string s1 to n. If
n<s1.length() s1 is truncated .if
n>s1.length() zeros are added to s1
11
OOP using JAVA
****************************************************************
Classes and Objects
Defining a Class
Definition:
The process of binding the data members and member functions into a
single unit is called as a class. In other words a class is a user defined data type.
Once the class type has been defined, we can create “variables” of that type. In
java these variables are termed as instances of classes, which are the actual
objects.
The basic form of a class definition is as follows
class clsname [ extends superclsname]
{
[fields declaration];
[methods declaration];
12
OOP using JAVA
}
Here, clasname and superclsname are any valid java identifiers. The
keyword extends indicates that the properties of the superclsname class are
extended to the clsname class. This concept is called as inheritance.
Everything inside the square brackets is optional. This means that the
following would be a valid class definition.
class clsname
{
}
Here, the body of the class is empty, this does not contain any properties
and therefore cannot do anything.
Fields Declaration
Data is encapsulated in a class by placing data fields inside the body of the
class definition. These variables are called instance variables because they are
created whenever an object of the class is instantiated. Instance variables are also
known as member variables. We can declare the instance variables exactly the
same way as we declare the local variables.
Example:
class Rectangle
{
int length;
int width;
}
The class Rectangle contains two integer type instance variables. Here,
these variables are only declared and therefore no storage space has been created
in the memory.
Methods Declaration
A class with only data fields has no life. The objects created by such a class
cannot respond to any messages.
Methods are declared inside the body of the class but immediately after the
declaration of instance variables. The general form of a method declaration is as
follows.
type methodname ( parameter_list)
{
Method-body;
}
13
OOP using JAVA
Creating Objects
An instance of a class is called as an object. An object in java is essentially
a block of memory that contains space to store all the member variables. Crating
an object is also referred to as instantiating an object.
Objects in java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.
Rectangle o1; //declaring the object
o1=new Rectangle(); // instantiate the object
The first statement declares a variable to hold the object reference and the
second one actually assigns the object reference to the variable. The variable o1
is now an object of the Rectangle class.
Both statements can be combined into one as shown below.
Rectangle o1=new Rectangle();
The method Rectangle ( ) is the default constructor of the class. We can
create any number of objects of Rectangle. For example
Rectangle o1= new Rectangle();
Rectangle o2= new Rectangle();
14
OOP using JAVA
It is important to understand that each object has its own copy of the
instance variable of its class. This means that any changes to the variables of one
object can have no effect on the variables of another.
It is also possible to create two or more references to the same object as
shown in below.
Rectangle R1=new Rectangle ();
Rectangle R2=R1;
15
OOP using JAVA
{
int area1, area2;
Rectangle r1=new Rectangle(); // Creating objects
Rectangle r2=new Rectangle();
area1=r1.len * r1.wid;
System.out.println("Area1=" + area1);
System.out.println("Area2=" + area2);
}
}
Output:
****************************************************************
Access Specifiers:
In Java, the access specifiers (also known as access modifiers) used to
restrict the scope or accessibility of a class, constructor, variable, method or
data member of class and interface. There are four access specifiers, and their
list is below.
default (or) no modifiers
public
protected
private
16
OOP using JAVA
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
****************************************************************
17
OOP using JAVA
static method:
It is a method which belongs to the class and not to the object(instance).
A static method can access only static data. It cannot access non-static data
(instance variables).
A static method can call only other static methods and cannot call a non-
static method from it.
A static method can be accessed directly by the class name and doesn’t
need any object.
18
OOP using JAVA
Output:
Static Block:
A static block is a block of statements declared as 'static', something like
this
static
{
statements;
}
JVM executes a static block on a highest priority basis. This means JVM
first goes to a static block even before it looks for the main( ) method in the
program.
Program:
class Demo
{
static
{
System.out.println("Static block");
}
public static void main(String args[ ])
{
System.out.println("Static method");
}
}
Output:
19
OOP using JAVA
****************************************************************
Constructors in Java.
Constructor:
Constructors are special methods having the same name as the class itself.
They do not have a return type, not even void.
A Constructor initializes an object automatically when the object is
created. Constructors can be overloaded like methods. The constructor is
automatically called when an object is created.
Java does three operations when new is used to create an instance of a class.
Allocates the memory for the object.
Initializes that objects instance variables, either to initial values or to a
default.
Calls the constructor of the class.
Constructors look a lot like regular methods with two basic differences.
Constructors always have the same name as that of class.
Constructor does not have a return type ( even void)
The following program illustrates the concept of constructors in java.
20
OOP using JAVA
Method Overloading
In java, it is possible to create methods that have the same name, but
different parameter list and different definitions. This is called method
overloading.
Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method in an object,
java matches up the method name first and then number and type of parameters
to decide which one of the definitions to execute. The methods return type does
not play any role in this.
21
OOP using JAVA
22
OOP using JAVA
Constructor Overloading
Like methods, constructors can also be overloaded. Appropriate
constructor is called as per the parameters we pass at the time of object creation.
In the following program, the constructor Demo() is overloaded 3 times.
Aim: To illustrate the concept of constructor overloading.
Program
//Demo.java
class Demo
{
int x,y;
Demo() // Default constructor
{
x=10;
y=20;
System.out.println("From default constructor");
}
Demo(int a) //Single parameterized constructor
{
x=a;
y=a;
System.out.println("From Single parameterized constructor");
}
Demo(int a, int b) //Double parameterized constructor
{
x=a;
y=b;
System.out.println("From double parameterized constructor");
}
void display()
{
System.out.println("The values are, x= " + x + " and y=" + y);
}
public static void main(String[] args)
{
Demo d1=new Demo(); //calling default constructor
d1.display();
Demo d2=new Demo(30); // calling Single parameterized
constructor
d2.display();
23
OOP using JAVA
****************************************************************
‘this’ keyword
In Java, this is a reference variable that refers to the current object.
Generally we write instance variables, constructors and methods in a class. All
these members are referenced by ‘this’. When an object is created to a class, a
default reference is also created internally to the object, as shown in fig.
Output:
****************************************************************
Inheritance
Definition:
The process of obtaining the data members and member functions from
one class to another class is known as Inheritance.
The class which is giving data members and member functions to some
other class is known as base/ super / parent class.
The class which is retrieving or obtaining the data members and member
functions is known as derived/sub/child class.
A Derived class contains some of features of its own plus some of
the data members from base class.
25
OOP using JAVA
Advantages of Inheritance
Application development time is less.
Application amount of memory space is less.
Redundancy (Repetition) of the code is reduced.
Syntax for INHERITING the features from base class to derived class:
class <clsname-2> extends <clsname-1>
{
Variable declaration;
Method definition;
}
Extends is a keyword which is used for inheriting the data members and
methods from base class to the derived class and it also improves functionality of
derived class.
Types of Inheritances (Reusable Techniques)
Based on getting the features from one class to some other class, in java
we have the following types of reusable techniques.
Single Inheritance (only one super class)
Multilevel Inheritance ( several super classes)
Multiple Inheritance (several super class, many sub classes)
Hierarchical Inheritance (one super class, many sub classes)
Single Inheritance
It is one it contains a single base class and a single derived class. It is shown
in below.
26
OOP using JAVA
class Room
{
float len, bre;
Room(float x, float y)
{
len=x;
bre=y;
}
float roomArea()
{
return (len*bre);
}
}
class BedRoom extends Room
{
float hei;
BedRoom(float x, float y, float z)
{
super(x,y);
hei=z;
}
float volume()
{
return (len*bre*hei);
}
}
class InheritTest
{
public static void main(String args[])
{
BedRoom r1=new BedRoom(12.2f,15.2f,10.3f);
float area=r1.roomArea();
float vol=r1.volume();
27
OOP using JAVA
Output:
Multilevel Inheritance
It is one in which it contains one base class and one derived class and
multiple intermediate base classes.( An intermediate base class is one, in one
context it acts as a derived class, in another context the same class acts as a base
class). It is shown in below.
Multiple Inheritance
It is one in which it contains multiple base classes and a s ingle derived
class. It is shown in below.
28
OOP using JAVA
****************************************************************
Super keyword in Java.
Subclass Constructor (‘super’ keyword):
A Subclass constructor is used to construct the instance variables of both
the subclass and the super class. The subclass constructor uses the keyword super
to invoke the constructor method of the super class. The super keyword is used
subject to the following conditions.
super may only be used within a subclass constructor method.
The call to super class constructor must appear as the first statement within
the subclass constructor.
The parameters in the super call must match the order and type of the
instance variables declared in the super class.
29
OOP using JAVA
}
Making a method as final ensures that the functionality in this method will
never be altered in any way. Similarly, the value of a final variable can never be
changed.
Final class:
If we don`t want to give features of base class to derived class then the
definition of the base class must be made as final.
Syntax: final class <clsname>
{
----------
}
Once the class is final, it never participates in inheritance process. In other
words final classes cannot be extended or inheritable.
Program:
final class Base
{
final void display()
{
System.out.println("This is a final method.");
}
}
class Derived extends Base
{
void display()
{
System.out.println("The final method is overridden.");
}
}
class Finaldemo
{
public static void main(String[] args)
{
Derived d = new Derived();
d.display();
final int x=10;
x=20;
}
}
30
OOP using JAVA
Output:
Note:
Final variable values cannot be modified.
Final methods cannot be overridden.
Final classes cannot be inheritable.
****************************************************************
Dynamic binding
Example :
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
public void draw() {
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape {
31
OOP using JAVA
In the above example, we have a Shape class and two subclasses: Circle
and Rectangle. Each subclass overrides the draw() method inherited from the
Shape class.In the main method, we created two shape objects: shape1 of type
Circle and shape2 of type Rectangle. Although the reference type is Shape, the
actual objects being referred to are Circle and Rectangle.
When we call the draw() method on shape1 and shape2, the JVM
dynamically binds the appropriate version of the draw() method at runtime based
on the actual type of the object.
Since shape1 refers to a Circle object, the draw() method in the Circle class
is invoked, and the output is "Drawing a circle". Similarly, since shape2 refers to
a Rectangle object, the draw() method in the Rectangle class is invoked, and the
output is "Drawing a rectangle".
This dynamic binding allows us to write code that works with a generic
reference type (Shape), but at runtime, the correct method implementation is
determined based on the actual object type being referred to. This flexibility and
polymorphic behaviour is one of the key advantages of dynamic binding in Java.
********************************************************
Method Overriding
The process of redefining the same method for many number of
implementations is called as method overriding.
32
OOP using JAVA
33
OOP using JAVA
}
}
Output:
****************************************************************
Abstract Methods and Classes
Abstract Method or Undefined method:
An abstract method is one which does not contain any definition/body but
it contains only prototype/declaration.
In order to make undefined methods as abstract methods, we need to write
abstract keyword before the method prototype.
Syntax for abstract method:
abstract return_type method_name ( list_args);
When we are declaring a method as an abstract method, that means, we can
indicate that a method must always be redefined in a subclass, thus making
overriding compulsory.
Example:
abstract void sum();
abstract void sum(int x, int y);
abstract class
If a class is containing one or more abstract methods then that class should
also be declared as an abstract class.
Syntax for abstract class
abstract class <clsname>
{
----------
abstract return_type method_name ( list_args);
---------
}
34
OOP using JAVA
Example
abstract class Base
{
abstract void calculate(int x);
}
class Derived1 extends Base
{
void calculate(int x)
{
System.out.println("Square="+(x*x));
}
}
class Derived2 extends Base
{
void calculate(int x)
{
System.out.println("Square root="+Math.sqrt(x));
}
}
Output:
35