Unit 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 67

UNIT-II

Constructor, Overloading, Garbage Collector, Importance of Static Keyword and this keywords,
Examples, Arrays, Command Line Arguments, Nested Classes.

Inheritance & Polymorphism: Basic concepts of Inheritance, Member access, forms of


inheritance- specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, Relationships, Creating Multilevel Hierarchy, super uses,
using final with Inheritance, Polymorphism, Runtime polymorphism, pure polymorphism,
method overriding, abstract classes & Methods, Object class

Packages: Defining a Package, PATH, CLASSPATH, Difference between PATH and CLASS
PATH, Access protection, importing packages.

Aim& objectives:

 Constructors are special function which is called automatically when we create object of
the class.
 Inheritance for the sole purpose of code reusability.
 The primary concern is that implementation inheritance does not provide any assurance
of polymorphic substitutability—an instance of the reusing class cannot necessarily be
substituted for an instance of the inherited class.
 Usage of arrays ,constructors in java coding
 De allocation of memory in garbage collection
 Passing values through command line

Constructors:

A constructor is special method which is invoked an object is initialized. It has following


features.

 In which constructor has the same name as class name. That is for example let us assume
a class with name Student the constructor of that class is as follows
Student( )
{

}
 Constructor has no return type even void. This is because the implicit return type of a
class’ constructor is the class type itself.
 Constructor is automatically called and executed at the time of creating an object. While
creating an object, if nothing is passed to the object, the default constructor is called and
executed. If some values are passed to the object, then the parameterized constructor is
called.

For example
Student s=new Student(); //Which invokes default constructor
Student s=new Student(name,28); // Which invokes default constructor

 Constructor is called and executed only once per object. This means when we create an
object, the constructor is called. When we create second object, again the constructor is
called second time.

Types of constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter. If you
don’t implement any constructor in your class, the Java compiler inserts default constructor
into your code on your behalf. You will not see the default constructor in your source
code(the .java file) as it is inserted during compilation and present in the bytecode(.class
file).

Syntax of default constructor:

<class_name>()

//example for initializing a default constructor


class Student
{

//instance variables
String name:
int rno;
//defaul t constr uct or
Student()
{
name= "Abhi";
rno=2;
}
/ /method
void study()
{
System.out.println("My name is "+ name);
System.out. println(“My roll no is "+ rno) ;
}
}
class ConDemo
{
public static void main (string args[ ])
{
//creating object one
Student one = new Student();
//call the study() method
one. study();
/ /create another object two
Student two= new Student();
//call the study() method
two. study();
}
}

Output:
C:\> javac ConDemo.java
C:\>java ConDemo
My name is Abhi
My roll no is 2
My name is Abhi
My roll no is 2

In the above example the objects have same values. To solve the problem let us try
parameterized constructor which accepts data from outside and initializes
instance variables with that data. Let us understand with an example.

Parameterized constructor

A constructor which has a specific number of parameters is called a parameterized constructor.


We can have any number of Parameterized Constructor in our class.
Why use the parameterized constructor?

The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.

//example for initializing a Parameterized constructor

class Student

//instance variables

String name:
int rno;
//default t constructor
Student()
{
name= "Abhi";
rno=2;
}
//parameterized constructor
Student(String a,int b)
{
name= a;
rno=b;
}

/ /method
void study()
{
System.out.println("My name is "+ name);
System.out. println(“My roll no is "+ rno) ;
}
}
class ConDemo
{
public static void main (string args[ ])
{
//creating object one
Student one = new Student();
//call the study() method
one. study();
/ /create another object two
Student two= new Student(“Ravi”,5);
//call the study() method
two. study();
}
}

Output:
C:\> javac ConDemo.java
C:\>java ConDemo
My name is Abhi
My roll no is 2
My name is Ravi
My roll no is 5

In the above example we solved the problem by giving different data.

Constructor-overloading
In Java it is possible to define two or more class constructors that share the same name, as long
as their parameter declarations are different. This is called constructor overloading when an
overloaded constructor is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded constructor to actually call. Thus, overloaded
constructors must differ in the type and/or number of their parameters
class Area{
double length;
double breadth;
// constructor used when all dimensions specified
Area(double l, double b, ) {
length = l;
breadth = b;
}
// constructor used when no dimensions specified
Area() {
length=1;
breadth=1;
}
// constructor with one parameter
Area(double len) {
Length=breadth = len;
}
// compute and return area of
double Areacal() {
return length*breadth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// invoking constructors
Area a1 = new Area(5,4);
Area a2= new Area(3);
Area a3 = new Area();
double area;
// get area of rectangle
area= a1.Areacal();
System.out.println("Area of rectangle is " + area);
// get area of square
area= a2.Areacal();
System.out.println("Area of square is " + area);
// get area of another square
area=a3.Areacal();
System.out.println("Area of another square is " + area);
}

Output:
The output produced by this program is shown here:
Area of rectangle is 20.0
Area of square is 9.0
Area of another square is 1.0

Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be wondering how
such objects are destroyed and their memory released for later reallocation. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. Java takes a different approach; it handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.It works like this: when no
references to an object exist, that object is assumed to be no longer needed, and the memory
occupied by the object can be reclaimed. There is no explicit
need to destroy objects as in C++. Garbage collection only occurs during the execution of your
program. The main job of this is to release memory for the purpose of reallocation. Furthermore,
different Java run-time implementations will take varying approaches to garbage collection
The finalize( ) Method
Sometimes an object will need to perform some action when it is destroyed. For example,if an
object is holding some non-Java resource such as a file handle or character font, then you might
want to make sure these resources are freed before an object is destroyed. To handle such
situations, Java provides a mechanism called finalization. By using finalization, you can define
specific actions that will occur when an object is just about to be reclaimed by the garbage
collector. To add a finalize to a class, you simply define the finalize( ) method. The Java run time
calls that method whenever it is about to recycle an object of that class. Inside the finalize( )
method, you will specify those actions that must be performed before an object is destroyed. The
garbage collector runs periodically, checking for objects that are no longer referenced by any
running state or indirectly through other referenced objects The finalize( ) method has this
general form:
protected void finalize ( )
{
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
Let us take an example
//example for garbage collection manually
Class Garb
{
protected void finalize ()
{
System.out.println(“Object is garbage collected”);
}
Public static void main(String args[])
{
Garb a1=new Garb();
Garb a2=new Garb();
a1=null;
a2=null;
System.gc();
}
}

Output:

Object is garbage collected


Object is garbage collected

In the above example null is used to remove the reference to object manually

static variables
static variable is common to all the instances (or objects) of the class because it is a class level
variable. In other words you can say that only a single copy of static variable is created and shared
among all the instances of the class. Memory allocation for such variables only happens once when
the class is loaded in the memory.
Like variables we can have static block, static method and static class.
Static variable Syntax
static keyword followed by data type, followed by variable name.

static data_type variable_name;

static variables are shared among all the instances of the class, they are useful when we need to do
memory management. In some cases we want to have a common value for all the instances like
global variable then it is much better to declare them static as this can save memory
example
class VariableDemo
{
static int count=0;
public void increment()
{
count++;
}
public static void main(String args[])
{
VariableDemo obj1=new VariableDemo();
VariableDemo obj2=new VariableDemo();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:

Obj1: count is=2


Obj2: count is=2

Static Methods:

Static methods are declared by using staic keyword


Static methods are called using Classname.methodname().
JVM first executes static method after only the objects are created. When the static methods are
called the instance variables and objects are not available
.
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
Let us take an example

//static method access instance variable


class Smeth
{
//staic varaible
staic double a=10;
//parameterized constructor
//static method accessing x
static void smethod() { .
System.out.println("a= "+a);
}
class Smain
{
public static void main(string args[])
{
Smeth s=new Smeth();
Smeth.smethod();
Output:
C:/> javac Smain.java
C:/>java Smain
a=10
The other name for static variable is 'class variable' and for static method is 'class method'.

static Block:
static block is a block of statements declared as static
static {
code;
}
JVM first looks for static block then only main will be executed. Static block has highest priority

//Static block or Static method?


c1ass Ss
{
Static
{
System.out.println(" First executes Static block’);
}
public static void main(String args[ ))
{
System.out.println("Next Static method");
}
}

Output:
C:/javac Ss.java
C:/>java Ss
First executes Static block
Next Static method
The this Keyword
Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. This is the instance of current class. That is, this is always a reference to the
object on which the method was invoked. You can use this any where a reference to an object of
the current class’ type is permitted, this is used to refer constructor instance variables and
methods of current class.

Instance variables

this Constructor

Methods

Fig: The keyword 'this' is a reference to class object


Let us take an example for this
//this - refers to all members of current class
class Thisdemo { .
//a is instance variable
String a;
//default constructor
Thisdemo()
{
this(“cse”) ; //call present class parameterized constructor
this.branch(); //call present class method
}
//parameterized constructor
Thisdemo(String a)
{
this.a = a; //refer present class instance variable
}
//method
void branch()
{
system.out.println("this is = "+a) ;
}
}
class Thismain
{
public static void main(String args[])
{
Thisdemo t= new Thisdemo() ;
}
c:\> javac Thismain.java
c:\> java Thismain
this is cse

In the above example this is used to refer default,parametrised constructor i.e. Thisdemo(),
Thisdemo(String a),method i.e. Branch(),instance variable i.e. a.

Arrays
An Array is a collection of elements of same type. The elements share the same name which can
be accessed by the index. To create an array, we must first create the array variable of the desired
type.
one dimensional array
A list of items group in a single variable name with only one index is called 1-D array.

The syntax of the One Dimensional array is as follows:


datatype variablename[];

1. creating an array
We can declare an array in java using subscript operator
datatype var_name[ ];

2. Declaring a variable to refer an array


An array declaration has two components: the type and the variable name. type declares the
element type of the array. The element type determines the data type of each element that
comprises the array. Like array of int type, we can also create an array of other primitive data
types like char, float, double..etc or user defined data type(objects of a class).Thus, the element
type for the array determines what type of data the array will hold.
Example:
int numbers[];
Here datatype is int, the variable name is numbers

3. Accessing an array element


In fact, the value of numbers is set to null, which represents an array with no value. To
link numbers with an actual, physical array of integers, you must allocate one using new
and assign it to numbers. new is a special operator that allocates memory dynamically.
The syntax of one-dimensional arrays with new operator is as follows:
array-var = new type[size];
Here, type specifies the type of data being allocated, size specifies the number of
elements in the array, and array-var is the array variable that is linked to the array. That
is, to use new to allocate an array, you must specify the type and number of elements to
allocate. The elements in the array allocated by new will automatically be initialized to
zero. This example allocates a 12-element array of integers and links them to numbers
numbers= new int[10];

numbers
Element 0 0 0 0 0 0 0 0 0 0
index 0 1 2 3 4 5 6 7 8 9

After this statement executes, numbers will refer to an array of 10 integers. Further, all
elements in the array will be initialized to zero.

Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets. All array indexes start at zero. For example,
this statement assigns the value 5 to the first element of numbers.
numbers[0] = 5;

Element 5 0 0 0 0 0 0 0 0 0
index 0 1 2 3 4 5 6 7 8 9

4. Array Initializers
In Java, you can initialize arrays during declaration or you can initialize (or change values) later in the
program as per your requirement.

Initialize an Array During Declaration


Here's how you can initialize an array during declaration.
int[] age = {12, 4, 5, 2, 5};

This statement creates an array and initializes it during declaration.

The length of the array is determined by the number of values provided which is
separated by commas. In our example, the length of age array is 5.

Let's write a simple program to print elements of this array.


class ArrayExample {
public static void main(String[] args) {

int[] age = {12, 4, 5, 2, 5};

for (int i = 0; i < 5; ++i) {


System.out.println("Element at index " + i +": " + age[i]);
}
}
}
Output:
Element at index 0: 12
Element at index 1: 4
Element at index 2: 5
Element at index 3: 2
Element at index 4: 5

Example Program: Write a Java Program to read elements into array and display them?

ArrayTest.java
import java.io.*;
class ArrayTest
{
public static void main(String args[]) throws IOException
{
DataInputStream dis=new DataInputStream(System.in);
int a[]; //declaring array variable
int n, i; //size of the array
System.out.println("Enter the size of Array:");
n=Integer.parseInt(dis.readLine());
a=new int[n]; //allocating memory to array a and all the elements are set zero
//read the elements into array
System.out.println("Enter the elements into Array:");
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(dis.readLine());
}
//displaying the elements
System.out.println("The elements of Array:");
for(i=0;i<n;i++)
{
System.out.print(a[i]+",");
}
}
}
Output:
C:/>javac ArrayTest.java
C:/>java ArrayTest
Enter the size of Array:
3
Enter the elements into Array:
15
36
78
The elements of Array:
15,36,78

Multidimensional Arrays:
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look
and act like regular multidimensional arrays. However, as you will see, there are a couple of
subtle differences. To declare a multidimensional array variable, specify each additional index
using another set of square brackets. For example, the following declares a two dimensional
array variable called twoD.
int twoD[][] = new int[4][4];
This allocates a 4 by 4 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.

Right Index Determines the


Columns
[0,0] [0,1] [0,2] [0,3]

[1,0] [1,1] [1,2] [1,3]


Left index
determines [2,0] [2,1] [2,2] [2,3]
the Rows
[3,0] [3,1] [3,2] [3,3]
Example Program for Matrix Addition
import java.io.*;
class AddMatrix
{
public static void main(String args[]) throws IOException
{
int m, n, c, d;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = Integer.parseInt(dis.readLine());
n = Integer.parseInt(dis.readLine());
int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = Integer.parseInt(dis.readLine());
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
second[c][d] = Integer.parseInt(dis.readLine());
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");
System.out.println();
}
}
}
output:
javac AddMatrix.java
java AddMatrix
Enter the number of rows and columns of matrix
2
3
Enter the elements of first matrix
1
3
4
5
6
7
Enter the elements of second matrix
1
2
3
4
5
6
Sum of entered matrices:-
2 5 7
9 11 13

Example program for Matrix Multiplication


import java.io.*;
class MulMatrix
{
public static void main(String args[]) throws IOException
{
int m, n, p, q, sum = 0, c, d, k;
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = Integer.parseInt(dis.readLine());
n = Integer.parseInt(dis.readLine());
int first[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = Integer.parseInt(dis.readLine());
System.out.println("Enter the number of rows and columns of second matrix");
p = Integer.parseInt(dis.readLine());
q = Integer.parseInt(dis.readLine());
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
System.out.println("Enter the elements of second matrix");
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = Integer.parseInt(dis.readLine());
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
System.out.println("Product of entered matrices:-");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
System.out.print("\n");
}
}
}
}
output:
java MulMatrix.java
java MulMatrix
Enter the number of rows and columns of first matrix
2
2
Enter the elements of first matrix
1
2
3
4
Enter the number of rows and columns of second matrix
2
2
Enter the elements of second matrix
1
2
3
4
Product of entered matrices:-
7 10
15 22

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the same
time. For example,
int[] nums, nums2, nums3; // create three arrays creates three array variables of type int. It is the
same as writing
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for a
method. Both forms are used.

Arrays of objects
Arrays are capable of storing objects also. For example, we can create an array of Strings which
is a reference type variable. However, using a String as a reference type to illustrate the concept
of array of objects isn't too appropriate due to the immutability of String objects
Syntax:
Class obj[]= new Class[array_length]

Example:

class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;//creates an array of two reference variables
obj[0] = new Account();//creates objects and assigns them to the reference variable array
obj[1] = new Account();//creates objects and assigns them to the reference variable array
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}
Output:
For Array Element 0
Value of a =1
Value of b =2
For Array Element 1
Value of a =3
Value of b =4

array of arrays (jagged array)


A jagged array in Java is a multi-dimensional array comprising arrays of varying sizes as its
elements. It’s also referred to as “an array of arrays” or “ragged array”.
we can create a 2-D arrays but with variable number of columns in each row. These type of arrays are
also known as Jagged arrays.
// Program to demonstrate 2-D jagged array in Java
class Main
{
public static void main(String[] args)
{
// Declaring 2-D array with 2 rows
int arr[][] = new int[2][];

// Making the above array Jagged

// First row has 3 columns


arr[0] = new int[3];

// Second row has 2 columns


arr[1] = new int[2];

// Initializing array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;

// Displaying the values of 2D Jagged array


System.out.println("Contents of 2D Jagged Array");
for (int i=0; i<arr.length; i++)
{
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output:
Contents of 2D Jagged Array
0 1 2
3 4

copying arrays
we can copy elements of array to another array as shown below
/ A Java program to demonstrate copying by one by one
// assigning elements of a[] to b[].
public class Test
{
public static void main(String[] args)
{
int a[] = {1, 8, 3};

// Create an array b[] of same size as a[]


int b[] = new int[a.length];

// Copy elements of a[] to b[]


for (int i=0; i<a.length; i++)
b[i] = a[i];

// Change b[] to verify that b[] is different


// from a[]
b[0]++;

System.out.println("Contents of a[] ");


for (int i=0; i<a.length; i++)
System.out.print(a[i] + " ");

System.out.println("\n\nContents of b[] ");


for (int i=0; i<b.length; i++)
System.out.print(b[i] + " ");
}
}
Output:
Contents of a[]
1 8 3

Contents of b[]
2 8 3

In the previous method we had to iterate over the entire array to make a copy, we can do better by clone
method.
Object cloning means to create an exact copy of the original object.

If a class needs to support cloning, it must implement java.lang.Cloneable interface and override clone()
method from Object class. Syntax of the clone() method is :
protected Object clone() throws CloneNotSupportedException
If the object’s class doesn’t implement Cloneable interface then it throws an exception
‘CloneNotSupportedException’ .
// A Java program to demonstrate array copy using clone()
public class Test
{
public static void main(String[] args)
{
int a[] = {1, 8, 3};

// Copy elements of a[] to b[]


int b[] = a.clone();

// Change b[] to verify that b[] is different


// from a[]
b[0]++;

System.out.println("Contents of a[] ");


for (int i=0; i<a.length; i++)
System.out.print(a[i] + " ");

System.out.println("\n\nContents of b[] ");


for (int i=0; i<b.length; i++)
System.out.print(b[i] + " ");
}
}
Output:
Contents of a[]
183

Contents of b[]
283

sorting array elements


Sorting means to put data in order; either numerically or alphabetically. There are many times
when it is necessary to put an array in order from highest to lowest (descending) or vice versa
(ascending). Because sorting arrays requires exchanging values, computers must use a special
technique to swap the positions of array elements so as not to lose any elements.
In java we have predefined class called Arrays in util package which have predefined methods
like sort ect.
// A sample Java program to sort an array of integers
// using Arrays.sort(). It by default sorts in
// ascending order
import java.util.Arrays;

public class SortExample


{
public static void main(String[] args)
{
// Our arr contains 8 elements
int[] arr = {13, 7, 6, 45, 21, 9, 101, 102};

Arrays.sort(arr);

System.out.printf("Modified arr[] : %s",


Arrays.toString(arr));
}
}
Output:
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

Example :
Without predefined functions
import java.util.Scanner;
public class Ascending _Order
{
public static void main(String[] args)
{
int n, temp;
Scanner s = new Scanner(System.in);//which takes input from keyboard
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
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;
}
}
}
System.out.print("Ascending Order:");
for (int i = 0; i < n - 1; i++)
{
System.out.print(a[i] + ",");
}
System.out.print(a[n - 1]);
}
}
Output:
javac Ascending _Order.java
java Ascending _Order

Enter no. of elements you want in array:5


Enter all the elements:
4
3
2
6
1
Ascending Order:1,2,3,4,6
Searching an array:
Searching is process of finding an element from array
Let us take example to search an element by using liner search
import java.util.Scanner;

class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];

Scanner in = new Scanner(System.in);


System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)


array[c] = in.nextInt();

System.out.println("Enter value to find");


search = in.nextInt();

for (c = 0; c < n; c++)


{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location
" + (c + 1) + ".");
break;
}
}
if (c == n) /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}
Output:
Enter 7 integers
4
6
2
1
8
9
3
Enter value to find
8
8 is present at location 5

Command Line arguments:


This are the values which are passed to mai() mrthod.In java main method has String args[] as
parameter which hold the command line values.
public static void main(String args [ ])
In the above statement args[] is one-dimensional array which hold String formatted values. The
arguments passed from the console can be received in the java program and it can be used as an
input. The first command line argument is stored in args[0], the second argument is stored in
args[1], the third argument is stored in args[2], and so on.
Example program:
Write a Java program to read all the command line arguments?
import java.io.*;
class CommnadLine
{
public static void main(String args[])
{
for(int i=0;i<args.length();i++)
{
System.out.println(“args[“+i”]=”+args[i]);
}
}
}
Output:
C:/>javac CommandLine.java
C:/>java CommandLine 2 3 4
args[0]=2
aargs[1]=3
args[2]=4

Here the String class has a method length(), which is used to find the length of the string. This
length can be used to read all the arguments from the command line.
Inner Class:
Inner class is a class written within another' class. Inner class is hidden from other classes in its
outer class. The instance variables not accessed outside the class if they are specified with
'private' access specifier. This is how we provide the security to variables. Similarly, if we
specify private before outer class then it is illegal because it is not access by JVM. But we can
specify inner class as private thus it is useful to provide security for entire inner class. Once
private is used before the inner class, it is not available to other classes .This means an object to
inner class cannot be created in any other class.

Let us take an example:


// Demonstrate an inner class.
class OutCls {
double outr_a = 45;
void test() {
Inner inn = new Inner();
inn.display();
}
// this is an inner class
class Inner {
void display() {
System.out.println("display: outr_a = " + outr_a);
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
OutCls o= new OutCls();
o.test();
}
}
Output :
C:/>javac InnerClassDemo.java
C:/>java InnerClassDemo
display: outr_a = 45

Types of inner classes


Inner class means one class which is a member of another class. There are basically four types of
inner classes in java.
1)Nested Inner class
2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes
Nested Inner class can access any private instance variable of outer class. Like any other
instance variable, we can have access modifier private, protected, public and default modifier.
Like class, interface can also be nested and can have access specifiers.
Following example demonstrates a nested class.
class Outer {
// Simple nested inner class
class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
Output:
In a nested class method

Method Local inner classes


Inner class can be declared within a method of an outer class. In the following example, Inner is
an inner class in outerMethod()
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}
Output
Inside outerMethod
Inside innerMethod
Method Local inner classes can’t use local variable of outer method until that local
variable is not declared as final
Static nested classes
Static nested classes are not technically an inner class. They are like a static member of outer
class.
class Outer {
private static void outerMethod() {
System.out.println("inside outerMethod");
}

// A static inner class


static class Inner {
public static void main(String[] args) {
System.out.println("inside inner class Method");
outerMethod();
}
}

}
Output
inside inner class Method
inside outerMethod

Anonymous inner classes


Anonymous inner classes are declared without any name at all. They are created in two ways.
a) As subclass of specified type
class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {

// An anonymous class with Demo as base class


static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}
Output
i am in show method of super class
i am in Flavor1Demo class

In the above code, we have two class Demo and Flavor1Demo. Here demo act as super class and
anonymous class acts as a subclass, both classes have a method show(). In anonymous class
show() method is overridden.
a) As implementer of the specified interface
class Flavor2Demo {

// An anonymous class that implements Hello interface


static Hello h = new Hello() {
public void show() {
System.out.println("i am in anonymous class");
}
};

public static void main(String[] args) {


h.show();
}
}

interface Hello {
void show();
}
Output:
i am in anonymous class
In above code we create an object of anonymous inner class but this anonymous inner class is an
implementer of the interface Hello. Any anonymous inner class can implement only one
interface at one time. It can either extend a class or implement interface at a time

Inheritance and polymorphism

Inheritance basics

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, you can add new methods and fields in your current class
also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Sub class and Super class

Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.

class Superclassname

Code;

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class

Syntax:

class Subclass extends Superclassname

{
Code;

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

Example

The following program creates a superclass called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A.

// Create a superclass.
class A
{
int i, j;

void showij() {

System.out.println("i and j: " + i + " " + j); } }


// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{

System.out.println("k: " + k); }


void sum()
{
System.out.println("i+j+k: " + (i+j+k));
}

}
class SimpleInheritance
{
public static void main(String args[])
{ // subclass object creation, which acquires all the properties of the superclass B
b = new B();
/* The subclass has access to all public members of its superclass. */
b.i = 7;
b.j = 8;
b.k = 9;
System.out.println("Contents of b: ");
b.showij();
b.showk();
System.out.println("Sum of i, j and k in b:");
b.sum(); } }
Output: Contents of b:
i and j: 7 8 k: 9
Sum of i, j and k in b: i+j+k: 24

Forms of inheritances:
Single Inheritance:
In this type of inheritance we have single super class and a single sub class.

Super class

Sub class

In the above figure sub class is called as derived class which acquires the properties of super
class i.e. the base class

Multilevel:

In this type of inheritance child class will be inheriting a parent class and as
well as the derived class act as the parent class to other class. let us see the diagram

B
C

In the above example class C is derived class which acquires the properties of base class B , A in
which B acts as derived class which acquires the properties of class A.

Syntax:

class A

Statements;

class B extends A

Code

class C extends B

Code;

Hierarchical:

In this type of inheritance it has one base class and n number of derived classes.

Animal

Dog Cat Cow


In the above example Animal is the base class in the classes Dog, Cat, Cow are derived classes
which acquires the properties of Animal class

Syntax:
Calss Animal
{
Code
}
Class Dog extends Animal
{
Code;
}
Class Cow extends Animal
{
Code;
}
Class Cat extends Animal
{
Code;
}

Multiple Inheritance :

It is the Inheritance which has many parent classes and one child here the child class tries to
acquire the properties of all the parent classes.

A B C

D
In the above figure class D is the child class which acquires the properties of the parent classes
like A,B and C.

Note:

Java does not support multiple inheritance because if two classes have same method with same
signature on calling the method the compiler cannot determine which class method is to be called
.But it can be achieved through interfaces.

Hybrid Inheritance:

Hybrid inheritance is the combination of Multiple and Simple (single) inheritance

B C

In the above figure class D is the derived class which acquires the properties of base classes like
B, C.And B,C Act as derived classes which acquires the properties of class A.

As java does not support multiple inheritances, the hybrid inheritance is also not supported as it
is the combination of Multiple and simple. So Hybrid can also achieve through interfaces only.
Member access and Inheritance

The following rules for inherited methods are enforced −


 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in subclasses;
they cannot be private.
 Methods declared private are not inherited at all, so there is no rule for them.

private member access


Although a subclass includes all of the members of its superclass, it cannot access those
members of the superclass that have been declared as private. The private members of the class
are accessed by the members of that class only, but are not accessed by the code outside that
class in which they are declared. For example, consider the following simple class hierarchy:
/* In a class hierarchy, private members remain private to their class. This program contains an
error and will not compile. */
// Create a superclass.
class A
{
double a; // public by default
private double b; // private to A
void setab(int x, int y)
{
a = x;
b = y;
}
}
// A's b is not accessible here.
class B extends A
{
int total;
void sum()
{
total = a + b; // ERROR, j is not accessible here
}
}
class Access
{
public static void main(String args[])
{
B b = new B(); // creating the object b
b.setab(10, 12);
b.sum(); // Error, private members are not accessed
System.out.println("Total is " + subOb.total);
}
}
Note:
This program will not compile because the reference to j inside the sum( ) method of B causes
an access violation. Since j is declared as private, it is only accessible by other members of its
own class. Subclasses have no access to it.

Inheritance for Specialization

The most common use of inheritance and sub classing is for specialization. The child class that is
created new is specialized variety of parent class. Thus, this form always creates a subtype, and
the principle of substitutability is explicitly upheld.

For example:

Class PpfAccount extends BankAccount

Code;

Here PpfAccount is the derived class which acquires the methods of BankAccount like withdraw
(), balance () ect. The subclass always satisfies the specification of its super class; i.e. the
subclass is a subtype.

Inheritance for specification:

This the most common use of inheritance. Two important mechanisms have been specified by
java those are abstract and interface to make use of sub class specification. This is actually a
special case of sub classing for specialization, except that the subclasses are not refinements of
an existing type but rather realizations of an incomplete abstract specification. That is, the parent
class defines the operation, but has no implementation. It is only the child class that provides an
implementation. In such cases the parent class is sometimes known as an abstract specification
class.

An interface is used to describe only the necessary requirements, and no actual behavior is
inherited by a subclass that implements the behavior.

For example

Class B implements A
{

//implements the methods A

Class A extends B

//class B is specified as abstract specification class

Inheritance for Construction:

A class can often inherit almost all of its desired functionality from a parent class, perhaps
changing only the names of the methods used to interface to the class, or modifying the
arguments. This may be true even if the new class and the parent class fail to share any
relationship as abstract concepts.
This type is mainly used for code reusability.

Example a Stack class defined in java library.

Inheritance for Extension:

Sub classing for extension occurs when a child class only adds new behavior to the parent class,
and does not modify or alter any of the inherited attributes. An example of inheritance for
extension in the Java library is the class Properties, which inherits from class HashTable. A hash
table is a dictionary structure that dictionary stores a collection of key/value pairs, and allows the
user to retrieve the value associated with a given key.

class Properties extends Hashtable

public synchronized void load(InputStream in) throws IOException

{... }

public synchronized void save(OutputStream out, String header)

{ ... }

}
As the functionality of the parent remains available and untouched, subclassing for extension
does not contravene the principle of substitutability and so such subclasses are always subtypes.

Inheritance for Limitation:

Subclassing for limitation occurs when the behavior of the subclass is smaller or more restrictive
than the behavior of the parent class. Like subclassing for extension, subclassing for limitation
occurs most frequently when a programmer is building on a base of existing classes that should
not, or cannot, be modified.

Suppose one wanted to create the class Set, in a fashion similar to the way the class Stack is
subclassed from Vector. However, you also wanted to ensure that only Set operations were used
on the set, and not vector operations. One way to accomplish this would be to override the
undesired methods, so that if they were executed they would generate an exception.

class Set extends Vector {

// isEmpty and size

// are all inherited from vector

public int indexOf (Object obj) {

throw new IllegalOperation("indexOf");

public int elementAt (int index) {

throw new IllegalOperation("indexOf"); }}

Where IllegalOperation is a subclass of Exception:

class IllegalOperation extends Exception }

IllegalOperation (String str) { super(str); }

Inheritance for Combination:

It is common for a new abstraction to be formed as a combination of features from two or more
abstractions. The properties are acquired by two or more parent classes is called multiple
inheritance. A teaching assistant, for example, may have characteristics of both a teacher and a
student, and can therefore logically behave as both.

As java does not support multiple inheritance it is archived by interfaces We saw this in the
example of the class Hole that both extended class Ball and implemented the interface for
PinBallTarget.

class Hole extends Ball implements PinBallTarget

{ ...

It is also possible for classes to implement more than one interface, and thus be viewed as a
combination of the two categories

The Benefits of Inheritance:

Java has many benefits the following are the benefits of java

 Software Reusability:
Java main feature is cod reusability. The code once written can be used many times.
Many programmers spend much of their time rewriting code they have written many
times before -for example, to search for a pattern in a string or to insert a new element
into a table. With object-oriented techniques, these functions can be written once and
reused.
 Increased Reliability:
Code that is executed frequently will tend to have fewer bugs then code that executed
infrequently. When the same components are used in two or more applications, the code
will be exercised more than code that is developed for a single application. Thus, bugs in
such code tend to be more quickly discovered, and latter applications gain the benefit of
using components are more error free.
 Code Sharing:
Code sharing is another important feature of java. In which the cod written once by a
programmer can be shared by others i.e. sharing occurs when two or more classes
developed by a single programmer as part of a project inherit from a single parent class. F
 Consistency of Interface
When two or more classes inherit from the same super class, we are assured that the
behavior they inherit will be the same in all cases. Thus, it is easier to guarantee that
interfaces to similar objects are in fact similar, and that the user is not presented with a
confusing collection of objects that are almost the same but behave, and are interacted
with, very differently.
 Software Components
Inheritance helps us to develop reusable software components. The Java library provides
a rich collection of software components for use in the development of applications.
 Rapid Prototyping
When a software system is constructed largely out of reusable components,
development time can be concentrated on understanding the new and unusual portion of
the system. Thus, software systems can be generated more quickly and easily, leading to
a style of programming known as rapid prototyping or exploratory programming.
 Polymorphism and Frameworks: Polymorphism in programming languages permits the
programmer to generate high-level reusable components that can be tailored to different
applications by changes in their low-level parts. The Java AWT is an example of a large
software framework that relies on inheritance and substitutability for its operation
 Information Hiding:
A programmer who reuses a software component needs only to understand the nature of
the component and its interface. It is not necessary for the programmer to have detailed
information concerning matters such as the techniques used to implement the component.
Thus, the interconnectedness between software systems is reduced. We earlier identified
the interconnected nature of conventional software as being one of the principle causes of
software complexity

Creating a Multilevel Hierarchy


In single inheritance we have only single base calss and single derived class.However, you can
build hierarchies that contain as many layers of inheritance as you like. For example, given three
classes called A, B, and C, C can be a subclass of B, which is a subclass of A. When this type of
situation occurs, each subclass inherits all of the traits found in all of its superclasses. In this
case, C inherits all aspects of B and A. To see how a multilevel hierarchy can be useful, consider
the following program.
Example program
class A
{
void methodA()
{
System.out.println("This is the method of A");
}
}
//class b extends the super class A
class B extends A
{
void methodB()
{
System.out.println("This is the method of B");
}
}
//class C extends the super class B
class C extends B
{
void methodC()
{

System.out.println("This is the method of C");


}
}
class Hierachy
{
public static void main(String args[])
{
C cobj=new C();
c.methodA();
c.methodB();
c.methodC();
}
}
Output:

C:/>javac Hirerachy.java

C:/>java Hirerachy

This is the method of A

This is the method of B

This is the method of C

Super class variable and sub class object

A reference variable of a superclass can be assigned a reference to any subclass derived from that
superclass. You will find this aspect of inheritance quite useful in a variety of situations. when a
reference to a subclass object is assigned to a superclass reference variable, you will have access only to
those parts of the object defined by the superclass.

For example,

class Box

double width,height,depth;
}

class Boxweight extends Box

double weight;

Boxweight(double x, double y, double z, double z)

{ width=x;

height=y;

depth=z;

weight=a;

void volume()

System.out.println("The volume is :"+(width*height*depth));

{ System.out.println("The volume is :"+(width*height*depth));

}}

//main class

class BoxDemo

//creating superclass object public static void main(String args[])

Box b=new Box();

//creating the subclass object Boxweight

bw=new Boxweight(2,3,4,5);

bw.volume();

//assigning the subclass object to the superclass object


b=bw;

// b has been created with its own data, in which weight is not a member

System.out.println ("The weight is :"+b.weight);

// here it raises error, super class does not contain the volume() method

}}

The uses of the "super" keyword

There are two uses of the super keyword.


i. super keyword is used to call the superclass constructor
ii. super keyword is used to access the members of the superclass.
Using the super to call the super class constructor
A subclass can call the constructor of the superclass by the using the super keyword in
thefollowing form:

super(arg_list);

class Teacher

Teacher()

System.out.println(“He is aTeacher”);

void college()

System.out.println(“He belongs to NRIIT”);

//sub calss

class Student extends Teacher


{

Student()

super();

super.college();//call parent class method

System.out.println(“He is Student”);

college();//calls current class method

super.college();//call parent class method

void college()

System.out.println(“He is Cse ”);

class Demo2

public static void main(String args[])

Student s=new Student();

Output:

He is Cse Student

He belongs to NRIIT

Using the super to access the super class members


The second form of super acts somewhat like this, except that it always refers to the superclass
of the subclass in which it is used. This usage has the following general form:
super.member;

Here, member can be either a method or an instance variable.


This second form of super is most applicable to situations in which member names of a subclass
hide members by the same name in the superclass. Consider this simple class hierarchy:
// Using super to overcome name hiding.
class A
{
int i;
}
// Create a subclass by extending class A.
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i = a; // i in A
i = b; // i in B
}
void show()
{
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper
{
public static void main(String args[])
{
B subOb = new B(1, 2);
subOb.show();
}
}
Output:

C:/>javac UseSuper.java

C:/>java UseSuper

i in superclass:1

i in subclass:2

Calling Constructor
The super keyword can also be used to invoke the parent class constructor.

Syntax:

super()

Let's see a simple example:

class Animal{
Animal()
{
System.out.println("animal is created");}
}
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
C:/>javac Test.java
C:/>java Test
animal is created
dog is created
Using final with Inheritance
The keyword final has three uses. First, it can be used to create the equivalent of a named
constant. The second is used to prevent the method overriding. The third, is used to prevent the
inheritance.
1. Creating the constant using final keyword
The final keyword can be used to create constants. The general form of the statement is as
follow:
final type variable_name=value;
where type can be any primitive data type, and variable_name can be any valid identifier. For
example,
final int speed=120;
2. Using final to Prevent Overriding
While method overriding is one of Java’s most powerful features, there will be times when you
will want to prevent it from occurring. To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a
compile-time error will result. Methods declared as final can sometimes provide a performance
enhancement: The compiler is free to inline calls to them because it “knows” they will not be
overridden by a subclass. When a small final method is called, often the Java compiler can copy
the bytecode for the subroutine directly in line with the compiled code of
the calling method, thus eliminating the costly overhead associated with a method call.
Inlining is only an option with final methods. Normally, Java resolves calls to methods
dynamically, at run time. This is called late binding. However, since final methods cannot be
overridden, a call to one can be resolved at compile time. This is called early binding.
3. Using final to Prevent Inheritance
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final,
too. As you might expect, it is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementations.
Here is an example of a final class:
final class A
{
// ...
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
// ...
}
As the comments imply, it is illegal for B to inherit A since A is declared as final.

Advantages of inheritance
 One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code exists
in two related classes, the hierarchy can usually be refactored to move the common code up to
a mutual superclass. This also tends to result in a better organization of code and smaller,
simpler compilation units.
 Inheritance can also make application code more flexible to change because classes that inherit
from a common superclass can be used interchangeably. If the return type of a method is
superclass
 Reusability - facility to use public methods of base class without rewriting the same.
 Extensibility - extending the base class logic as per business logic of the derived class.
 Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class
 Overriding -With inheritance, we will be able to override the methods of the base class so
that meaningful implementation of the base class method can be designed in the derived class.

Dynamic Method Binding

Polymorphism:

It is a Greek word in which ploy means many, morphism means forms.In which it ability to show
one thing in many forms. For example, we use mobile for communication. The communication
mode we choose could be anything. It can be a call, a text message, a picture message, mail, etc.
So, the goal is common that is communication, but their approach is different. This is
called Polymorphism

There are two types of polymorphism in Java:

 compile-time polymorphism
 runtime polymorphism.

We can perform polymorphism in java by method overloading and method overriding. f you
overload a static method in Java, it is the example of compile time polymorphism

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.
Let’s begin by restating an important principle: a superclass reference variable can refer to a
subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here is
how. When an overridden method is called through a superclass reference, Java determines
which version of that method to execute based upon the type of the object being referred to at the
time the call occurs. Thus, this determination is made at run time.
Here is an example that illustrates dynamic method dispatch:
// Dynamic Method Dispatch or run-time polymorphism
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");
}
}
class Dispatch
{
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
}
}
The output from the program is shown here:
Inside A’s callme method

Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden. Consider the following example:
class A
{
void disp()
{
System.out.println("This is the class A method");
}
}
// extending the superclass properties
class B extends A
{
void disp()
{
System.out.println("This is the class B method");
}
}
// main class
class OverRide
{
public static void main(String args[])
{
B b=new B();
b.disp(); // super class method is hidden, subclass method is invoked
}
}
output:
This is the class B method
Inside B’s callme method
Inside C’s callme method

Restrictions on overriding methods

 Overriding methods must have the same name, parameter list, and same return type. i.e.,
they must have the exact signature of the method we are going to override, including
return type.
 The overriding method cannot be less visible than the method it overrides. i.e., a public
method cannot be override to private
 The overriding method may not throw any exceptions that may not be thrown by the
overridden method.

Difference between overloading and overriding


1. Overloading happens at compile-time while Overriding happens at runtime: The binding of
overloaded method call to its definition has happens at compile-time however binding of
overridden method call to its definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one static method
of same name. Static methods cannot be overridden, even if you declare a same static method
in child class it has nothing to do with the same method of parent class.
3. The most basic difference is that overloading is being done in the same class while for
overriding base and child classes are required. Overriding is all about giving a specific
implementation to the inherited method of parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being used for
overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The reason is that
the binding of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It means a class
can have more than one private/final methods of same name but a child class cannot override
the private/final methods of their base class.
7. Return type of method does not matter in case of method overloading, it can be same or
different. However in case of method overriding the overriding method can have more specific
return type
8. Argument list should be different while doing method overloading. Argument list should be
same in method Overriding.

Using Abstract Classes


Sometimes it may be need by the super class to define the structure of the every method without
implementing it. The subclass can fill or implement the method according to its requirements.
This kind of situation can come into picture whenever the superclass unable to implement the
meaningful implementation of the method. For example, if we want to find the area of the Figure
given, which can be Circle, Rectangle, and Traingle. The class Figure
defines the method area(), when subclass implements its code it implements its own version of
the method. The Java's solution to this problem is abstract method.
To declare an abstract method, use this general form:

abstract type name(parameter-list);

abstract classes
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and
non-abstract methods. There can be no objects of an abstract class. That is, an abstract class cannot
be directly instantiated with the new operator. Such objects would be useless, because an abstract
class is not fully defined.

abstract class Figure


{
double a;
abstract void area();
}
//extending the super class
class Circle extends Figure
{ double r;
Circle(double x)
{
r=x;
}
//CIrcle implementing its own method
void area()
{
a=3.14*r*r;
System.out.println("The area of the circle is :"+a);
}
}
//Extending the super class
class Triangle extends Figure
{ double l,b;
Triangle(double x,double y)
{
l=x;
b=y;
}
//Triangle implementing its own method
void area()
{
a=l*b;
System.out.println("The area of the traingle is :"+a);
}
}
class FigureDemo
{
public static void main(String args[])
{

Circle c=new Circle(4.5);


c.area();
Triangle t=new Triangle(2,3);
t.area();
}
output:
javac FigureDemo.java
java FigureDemo
The area of the circle is:63.585
The area of the traingle is :6.0
Object classes:

Object class is root class for all other classes. This means that a reference variable of type
Object can refer to an object of any other class

Object defines the following methods, which means that they are available in every object

Object clone( ) Creates a new object that is the same as the


object being cloned
void finalize( ) Called before an unused object is recycled.

Class getClass( ) Obtains the class of an object at run time.

boolean equals(Object object) Determines whether one object is equal to


another.

void wait( ) Waits on another thread of execution


void wait(long milliseconds)
void wait(long milliseconds,
int nanoseconds)

void notifyAll( ) Resumes execution of all threads waiting on


the invoking object.

void notify( ) Resumes execution of a thread waiting on the


invoking object.

int hashCode( ) Returns the hash code associated with the


invoking object.

String toString( ) Returns a string that describes the object.

methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override
the others. These methods are described elsewhere in this book. However, notice two methods
now: equals( ) and toString( ). The equals( ) method compares the contents of two objects. It
returns true if the objects are equivalent and false otherwise

In this unit we gained knowledge about constructor and types of constructors ,and how the
memory was deallocate in java ,we also learnt that arrays are very useful for ,a programmer to
handle a group elements easily, In Java, we got Static methods,instance methods ,the values can
also be passed dynamically by using command line arguments.When the programmer wants to
restrict the access of entire code of a class, he creates an inner class as a private class. so we can
access the inner class is through its outer class only and authentication mechanism is
implemented in the outer class.

Review Questions
-------------------------
1. Write about multidimensional arrays in java.
2. What is the importance of constructor? Write a java program to perform constructor
overloading.
3. Write about command line arguments.
4. What is method overriding? Illustrate the concepts of method overriding and constructor
overriding.
5. With suitable program segments describe the usage of ‘super’ keyword.
6. What is a nested class? Differentiate between static nested classes and non-static nested
classes.
7. Distinguish between abstract class and concrete class.
8. Explain the various access specifiers are used in java
9. Explain multilevel inheritance with the help of abstract class in your program
10. What is meant by dynamic method dispatch? Explain with a program.
11. What is inheritance? Explain different forms of inheritance with suitable program segments
and real world example classes
12. Explain the use of ‘this’ keyword.
13. Write about garbage collection in Java.

Programs related to the topics discussed in this unit>>>>>


---------------------------------------------------------------------------
1. Write a java program that inputs an integer, ‘n’ from the command line and displays the
string “1+2+3+…+n=sum” and also compute the sum.
2. Do you need to use static keyword for the above bank account program? Explain
3. Describe the usage of static members and nesting members with suitable example programs
in java.
4. By using command line arguments Accept the input from keyboard to display Fibonacci
series.
5. Explain the different types of constructors with an example.
6. Write a program to find the transpose of a given matrix.
7. Write a runtime polymorphism program in Java by using interface reference variable.
8. Write inheritance hierarchy for the super class Quadrilateral, Parallelogram, Square and
Rectangle. Calculate area of square, rectangle and parallelogram
9. write aprogram to print
1
12
123
1234

Multiple Choice Questions


-----------------------------------
1. What is true about private constructor?
a) Private constructor ensures only one instance of a
class
exist at any point of time
b) Private constructor ensures multiple instances of
a class
exist at any point of time
c) Private constructor eases the instantiation of a
class
d) Private constructor allows creating objects in
other
classes
2. What would be the behaviour if this() and super()
used in a method?
a) Runtime error

b) Throws exception
c) compile time error
d) Runs successfully
3. What is false about constructor?
a) Constructors cannot be synchronized in Java
b) Java does not provide default copy constructor
c) Constructor can be overloaded
d) “this” and “super” can be used in a constructor
4. What is true about Class.getInstance()?
a) Class.getInstance calls the constructor
b) Class.getInstance is same as new operator
c) Class.getInstance needs to have matching
constructor
d) Class.getInstance creates object if class does not
have
any constructor
5. What is true about constructor?
a) It can contain return type

b) It can take any number of parameters


c) It can have any non access modifiers
d) Constructor cannot throw an exception
6. Abstract class cannot have a constructor.
a) True
b) False
7. What is true about protected constructor?
a) Protected constructor can be called directly
b) Protected constructor can only be called using
super()
c) Protected constructor can be used outside
package
d) protected constructor can be instantiated even if
child is in a different package
8. What would be behaviour if the constructor has a
return type?
a) Compilation error
b) Runtime error

c) Compilation and runs successfully


d) Only String return type is allowed
9.What is the process of defining two or more
methods within same class that have same name
but different parameters declaration?
a) method overloading
b) method overriding
c) method hiding
d) none of the mentioned
10. Which of these can be overloaded?
a) Methods
b) Constructors
c) All of the mentioned
d) None of the mentioned
11.What is the output of this program?
class overload
{
int x;

int y;
void add(int a)
{
x = a + 1;
}
void add(int a, int b)
{
x = a + 2;
}
}
class Overload_methods
{
public static void main(String args[])
{
overload obj = new overload();
int a = 0;
obj.add(6);

System.out.println(obj.x);
}

}
a) 5
b) 6
c) 7
d) 8
12.Which of the following is a garbage collection
technique?
a) Cleanup model
b) Mark and sweep model
c) Space management model
d) Sweep model
13.Garbage Collection can be controlled by a
program?
a) True
b) False
14. What is the return type of Constructors?

a) int
b) float
c) void
d) none of the mentioned
15:Which keyword is used by the method to refer to
the object that invoked it?
a) import
b) catch
c) abstract
d) this
16.Which of the following statements are incorrect?
a) default constructor is called at the time of object
declaration
b) Constructor can be parameterized
c) finalize() method is called when a object goes out
of scope and is no longer needed
d) finalize() method must be declared protected
17.Which one of the following is not an access

modifier?
a) Public
b) Private
c) Protected
d) Void
18.Which of these keywords is used to prevent
content of a variable from being modified?
a) final
b) last
c) constant
d) static
19.Which of these cannot be declared static?
a) class
b) object
c) variable
d) method
20.Which of these methods must be made static?
a) main()

b) delete()
c) run()
d) finalize()
21.what is the use of this keyword?
a)this can be used to refer current class instance
variable.
b)this can be used to invoke current class method
(implicitly)
c)this can be passed as an argument in the method
call.
d)all of the above.
22.Arrays in Java are implemented as?
a) class
b) object
c) variable
d) none of the mentioned
23.What is the output of this program?
class Output

{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
for ( int i = 0; i < arr.length - 2; ++i)
System.out.println(arr[i] + " ");

}
}
a) 1 2
b) 1 2 3
c) 1 2 3 4
d) 1 2 3 4 5
24.Which of this method is given parameter via
command line arguments?
a) main()
b) recursive() method
c) Any method
d) System defined methods

25.How many arguments can be passed to main()?


a) Infinite
b) Only 1
c) System Dependent
d) None of the mentioned
26.Which of these is a correct statement about args
in this line of code?
public static void main(String args[])
a) args is a String
b) args is a Character
c) args is an array of String
d) args in an array of Character
27.. What is the output of this program, Command
line execution is done as “java Output This is a
command Line”?
class Output
{
public static void main(String args[])

{
System.out.print("args[0]");
}
}
a) java
b) Output
c) This
d) is
28.how many types of nested classes in java?
a)2
b)4
c)1
d)5
29.Can we access non-static members of outer
class inside a static nested class?
a)yes
b)no
c)none

d)a&b
30.How to Create Anonymous Class in Java?
a)Using Class
b) Using Interface
c)both class and interface
d)none
31.Output of follwoing Java program
class Main {
public static void main(String args[]){
final int i;
i = 20;
System.out.println(i);
}
}
a)20
b)Compiler Error
c)0

d)Garbage value
32. Which of these class is superclass of every class
in Java?
a) String class
b) Object class
c) Abstract class
d) ArrayList class
33.What is the output of this program?
abstract class A
{
int i;
abstract void display();
}
class B extends A
{
int j;
void display()
{

System.out.println(j);
}
}
class Abstract_demo
{
public static void main(String args[])
{
B obj = new B();
obj.j=2;
obj.display();
}
}
a) 0
b) 2
c) Runtime Error
d) Compilation Error
34. Which of these keywords can be used to prevent
inheritance of a class?

a) super
b) constant
c) class
d) final
35. Which of this keyword can be used in a subclass
to call the constructor of superclass?
a) super
b) this
c) extent
d) extends
36.What is the process of defining a method in a
subclass having same name & type signature as a
method in its superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
37.Which of these is supported by method overriding

in Java?
a) Abstraction
b) Encapsulation
c) Polymorphism
d) None of the mentioned
38.What is the output of this program?
class A
{
int i;
public void display()
{
System.out.println(i);
}
}
class B extends A
{

int j;

public void display()


{
System.out.println(j);
}
}
class Dynamic_dispatch
{

public static void main(String args[])


{
B obj2 = new B();
obj2.i = 1;
obj2.j = 2;
A r;
r = obj2;
r.display();
}

a) 1
b) 2
c) 3
d) 4
39. Which of these keywords are used to define an
abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class
40. Which of these is not a correct statement?
a) Every class containing abstract method must be
declared abstract
b) Abstract class defines only the structure of the
class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
41. Which of these packages contains abstract

keyword?
a) java.lang
b) java.util
c) java.io
d) java.system
42. What is the output of this program?
class A
{
public int i;
public int j;
A()
{

i = 1;
j = 2;

}
}
class B extends A

{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}

}
a) 1 2
b) 2 1

c) Runtime Error
d) Compilation Error
43.What is the return type of a method that does not
return any value?
a) int
b) float
c) void
d) double
44.Which of this statement is incorrect?
a) All object of a class are allotted memory for the
all the variables defined in the class
b) If a function is defined public it can be accessed
by object of other class by inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the
methods defined in the class
45.Which of these is correct way of inheriting class
A by class B?
a) class B + class A {}

b) class B inherits class A {}


c) class B extends A {}
d) class B extends class A {}
46. Which of this keyword must be used to inherit a
class?
a) super
b) this
c) extent
d) extends
47. What is not type of inheritance?
a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance
48. Using which of the following, multiple inheritance
in Java can be implemented?
a) Interfaces
b) Multithreading

c) Protected methods
d) Private methods
49.Which of the following is used for implementing
inheritance through an interface?
a) inherited
b) using
c) extends
d) implements
50.What is the output of this program?
class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A

{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}

}
a) 0
b) 1
c) 2
d) Compilation Error
51.What do you call the languages that support
classes but not polymorphism?
a) Class based language
b) Procedure Oriented language
c) Object-based language
d) If classes are supported, polymorphism will
always be supported
52.Which among the following is the language which
supports classes but not polymorphism?
a) SmallTalk
b) Java
c) C++
d) Ada
53. Which type of function among the following

shows polymorphism?
a) Inline function
b) Virtual function
c) Undefined functions
d) Class member functions
54.. Which among the following cant be used for
polymorphism?
a) Static member functions
b) Member functions overloading
c) Predefined operator overloading
d) Constructor overloading
55. Which among the following can show
polymorphism?
a) Overloading ||
b) Overloading +=
c) Overloading <<
d) Overloading &&
56. How many types of inheritance are possible in

C++?
a) 2
b) 3
c) 4
d) 5
57. Which type of inheritance results in diamond
problem?
a) Single level
b) Hybrid
c) Hierarchical
d) Multilevel
58.Which type of inheritance cannot involve private
inheritance?
a) Single level
b) Multiple
c) Hybrid
d) All types can have private inheritance
59. Diamond problem includes ____________________

hybrid inheritance
a) Hierarchical and Multiple
b) Hierarchical and Hierarchical
c) Multiple and Multilevel
d) Single, Hierarchical and Multiple
60. If hybrid inheritance is used, it mostly shows
_______________ feature of OOP.
a) Flexibility
b) Reusability
c) Efficiency
d) Code readability

answers:

1.a 21.d 41.a


2.c 22.b 42.a
3.c 23.b 43.c
4.d 24.a 44.d
5.b 25.a 45.c

6.b 26.c 46.d

7.b 27.c 47.b

8.a 28.a 48.a

9.a 29.b 49.d


10.c 30.c 50.c

11.c 31.a 51.c

12.b 32.b 52.d

13.b 33.b 53.b

14.d 34.d 54.a

15.d 35.a 55.c

16.c 36.b 56.d

17.d 37.c 57.b

18.a 38.b 58.d

19.b 39.b 59.a

20.a 40.c 60.b

You might also like