Professional Documents
Culture Documents
Inheritance
What is an inheritance? Explain types of inheritance?
Inheritance:
The mechanism of creating a new class from an old class is called inheritance. Or
creating a new version for an existing class. Inheritance allows subclasses to inherit
all the variables and methods of their parent classes.
In the terminology of Java, a class that is inherited is called a super class. The class
that does the inheriting is called a subclass.
To inherit a class, we use the extends keyword. The general form of a class
declaration that inherits a superclass is
class subclass-name extends superclass-name
{
// body of class
}
The inheritance process can not extend private members , static members , constructor
methods of super class into sub class.
Inheritance may take different forms
1. Single inheritance
2. Multi level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
In Java we can extend only one class at a time. That‟s why in java we can not find
multiple inheritance and hybrid inheritance.
Single Inheritance:
If the inheritance process has only one super class and one sub class (one level ) then it is
called single level or simple inheritance.
Example:
class A{
int i,j;
void showij( ){
System.out.println("i and j : "+i+" "+j);
}
}
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 single {
public static void main ( String args [ ] ) {
B ob2=new B();
ob2.i=10;
ob2.j=20;
ob2.k=30;
System.out.println("Contents of ob2 :");
ob2.showij( );
ob2.showk( );
ob2.sum( );
}
}
Vasavi Degree College (C) www.anuupdates.org 2
KHK JAVA Unit-3
Multilevel Inheritance
A common requirement in object-oriented programming is the use of a derived class as a
super class. Java supports this concept and uses it extensively in building its class library. In
multi level inheritance the sub class may act as a super class for another sub class.
SALES
|
|
ITEMS_RATE
|
|
AMOUNT
The class SALES serves as a base class for the derived class ITEMS_RATE which in turn
serves as a base class for the derived class AMOUNT. The class ITEMS_RATE is known as
intermediate base class since it provides a link for the inheritance between SALES and
AMOUNT. The chain SALES ITEMS_RATE AMOUNT is known as inheritance path.
Example:
import java.util.*;
class SALES {
int sno;
void input (int a) {
sno=a;
}
}
class mlevel {
public static void main ( String args[ ] ) {
AMOUNT amt=new AMOUNT( );
System.out.println("Enter Salesmen Number,number of items,rate");
Scanner sc = new Scanner(System.in);
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
amt.input(a);
amt.accept(b,c);
amt.cal_print();
}}
Hierarchical Inheritance
Another interesting application of inheritance is to use it as a support to the
hierarchical design of a program. Many programming problems can be cast into a
hierarchy where certain features of one level are shared by many others below the
level. The common base class supplies its properties to the sub classes which below
the level.
Shape
Circle Rectangle
class shape {
double dim1,dim2;
double area( ){}
}
class Rectangle extends shape {
Rectangle(double a, double b)
{
dim1=a;
dim2=b;
}
double area ( ) {
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
dim1=a;
dim2=b;
}
double area ( ) {
return dim1 * dim2 / 2;
}
}
class hierar {
public static void main ( String args[ ] ) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
System.out.println("Area is " + r.area( ));
System.out.println("Area is " + t.area( ));
}
}
m1=c;
m2=d;
m3=e;
}
void print ( ){
display ( );
System.out.println("Total "+(m1+m2+m3));
}}
class super_demo1{
public static void main (String args [ ]) {
Marks M = new Marks(100,"hari",90,90,90);
M . print ( );
}}
syntax: .
super member
}}
class super_demo2{
public static void main ( String args[ ] ) {
B obj=new B(10,20);
obj.show( );
}}
class override_demo {
public static void main ( String args [ ]) {
B obj=new B(10,20,30);
obj.show( );
}}
Example:
abstract class A {
abstract void callme( );
void callmetoo( ) {
System.out.println("This is a concrete method.");
} }
class B extends A {
void callme ( ) {
System.out.println ("B's implementation of callme.");
}}
class abst{
public static void main ( String args [ ] ) {
B b = new B();
b.callme ( );
b.callmetoo();
}}
}
double area ( ) {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
} }
class dyna_bind{
public static void main ( String args[ ] ) {
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure f;
f = r;
System.out.println("Area is " + f.area());
f = t;
System.out.println("Area is " + f.area());
} }
Arrays
What is an array? Explain How to create an array?
Array:
An array is a collection similar data item arranged in a sequential order in the memory
and shares the same name. To refer to a particular location or element in the array, we
specify the name of the array and the index of the particular element in the array, the
index starts from 0 and ends with size-1. Arrays can be of any variable type. Arrays
are created on dynamic memory by JVM.
Types of Arrays:
Arrays are generally categorized into two parts as described here:
1. Single dimensional arrays.(or 1D arrays)
2. Multidimensional arrays.(or2D , 3D ,.. arrays)
One-Dimensional Arrays
A list of items can be given one variable name using only one subscript ( [ ] ) and
such a variable is called a single-subscripted variable or a one-dimensional array. To
create an array in Java, you use three steps:
1. Declare a variable to hold the array.
2. Create a new array object and assign it to the array variable.
3. Store things in that array.
Declaring Array Variables
Array variables indicate the type of object the array will hold and the name of the array,
followed by empty brackets ( [ ] ).
type arrayname [ ];
or
type [ ] arrayname;
Ex:
int a[ ];
float [ ] b;
Creation of memory locations for an array variable:
After declaring an array, we need to create it in the memory. Java allows us to create
arrays using new operator , as shown below:
When you create an array object using new, all its elements are initialized by their
default values.
We can also allocate and initialize the elements of an array in the array declaration by
following the declaration a comma-separated list of values enclosed in braces ({ and }).
For example, the declaration
int n[ ] = { 10, 20, 30, 40, 50 };
creates a five-element array with subscripts of 0, 1, 2, 3 and 4. Note that the preceding
declaration does not require the new operator to create the array object.
Accessing Array Elements
Once you have an array with initial values, you can test and change the values in each
slot of that array. To get at a value stored within an array, use the array subscript
expression:
myArray [subscript];
The myArray is the array name and subscript is index number of the element which we
want to access
Multi-Dimensional Arrays:
Multi dimensional arrays represent 2D, 3D … arrays. A two dimensional array is a
combination of two or more (1D) one dimensional arrays. A three dimensional array
is a combination of two or more (2D) two dimensional arrays.
Two Dimensional Arrays (2d array):
A two dimensional array represents several rows and columns of data. To represent a
two dimensional array, we should use two pairs of square braces [ ] [ ] after the array
name.
We can create a two dimensional array by declaring the array first and then we can
allocate memory for it by using new operator as:
int marks[ ] [ ]; //declare marks array
marks = new int[2][3]; //allot memory for storing 6 elements.
We can declare a two dimensional array and directly store elements at the time of its
declaration, as:
int marks[ ] [ ] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
To get at a value stored within a two dimensional array, use the array subscript
expression:
Arr_name [row] [col];
Three Dimensional arrays (3D arrays):
We can consider a three dimensional array as a combination of several two
dimensional arrays. To represent a three dimensional array, we should use three pairs
of square braces ( [ ] ) after the array name.
We can declare a three dimensional array and directly store elements at the time of its
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
We can create a three dimensional array by declaring the array first and then we can
allot memory for it by using new operator as:
int arr[ ] [ ] = new int[2][2][3]; //allot memory for storing 12 elements.
What is Variable Size Arrays?
This type of array is also called as “jagged array” and each row consists variable no of
columns. To allocate memory for a jagged array, you need only specify the memory
for the first dimension only. You can allocate the remaining dimensions separately.
This means you can construct arrays as you like.
Example:
int x[ ][ ]=new int [3][ ];
x[0]=new int[4];
x[1]=new int[2];
x[2]=new int[7];
x[1][0] x[1][1]
Example-1:
import java.util.*;
class arr1{
public static void main(String args[ ] ){
int a[ ]=new int[5];
Scanner sc = new Scanner(System.in);
int i;
System.out.println("Enter array elements :");
for(i=0;i<a.length;i++)
a[i]=sc.nextInt();
System.out.print("The given Elements are : ");
for(i=0;i<a.length;i++)
System.out.print(a[i] +" ");
}
}
Output:
Enter array elements :
10 20 30 40 50
The given Elements are : 10 20 30 40 50
Example-2:
class arr2{
public static void main(String args[ ]) {
int a[ ]={10,20,30};
System.out.print("The array elements are : ");
for(int i=0;i<a.length;i++)
System.out.print(a[i] +" ");
}
}
Output:
The array elements are : 10 20 30
Example-3:
Write a program to reverse an array
import java.util.*;
class revarray {
public static void main(String args[ ] ){
int a[]= new int[5];
int i,temp;
Scanner sc= new Scanner (System.in);
System.out.println("Enter 5 elements");
for(i=0; i<a.length; i++)
a[i]= sc.nextInt();
for(i=0; i<(a.length/2); i++) {
temp=a[i];
a[i]=a[4-i];
a[4-i]=temp;
}
System.out.print("The reverse of the array : ");
for(i=0;i<5;i++)
System.out.print(a[i] + " ");
}
}
Output:
Enter 5 elements
10 20 30 40 50
The reverse of the array : 50 40 30 20 10
Example-4
Write a program to delete a number from array of elements
import java.util.*;
class del_arr {
public static void main(String arg[ ]) {
int a[ ];
Scanner sc = new Scanner(System.in);
int i,n=0,q=0;
int ctr=0;
System.out.print("Enter no. of elements ");
n = sc.nextInt();
a= new int[n];
System.out.printf("Enter %d elements ",n);
for(i=0;i<n;i++)
a[i]=sc.nextInt();
System.out.println("Enter element to be deleted ");
q=sc.nextInt();
for(i=0;i<n;i++) {
if(a[i]==q) {
for (int k=i;k<n-1;k++)
a[k]=a[k+1];
ctr++;
} }
if(ctr==0)
System.out.println("Element not found");
else {
for(i=0;i<(n-ctr);i++)
System.out.print(a[i]+"\t");
} } }
Output:
Enter no. of elements 5
Enter 5 elements 10 20 30 40 50
Enter element to be deleted 20
10 30 40 50
Example-5:
class Matrix{
public static void main(String args[ ]){
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
for (int i = 0 ; i < 2 ; i++){
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] +" " );
System.out.println( );
}}}
Output:
1 2 3
4 5 6
Example-6
Write a program to perform matrix multiplication
import java .util.*;
class matrix_mul {
public static void main(String args[ ]) {
int a[ ][ ],b[ ][ ],c[ ][ ];
int m,n,o,p,s,i,j,k;
Scanner sc = new Scanner (System.in);
System.out.println("Enter first matrix dimension");
m=sc.nextInt( );
n=sc.nextInt( );
System.out.println("Enter second matrix dimension");
o=sc.nextInt( );
p=sc.nextInt( );
if(n!=o) {
Strings
What is a string and explain different ways to creation of strings?
Or
What is a string and explain string class constructors?
Strings represent a sequence of characters. A Java string is an instantiated object of
the String class. Java strings, as compared to C strings, are more reliable and
predictable. A Java string is not a character array and is not NULL terminated. String
is a class in java.lang package and the java strings are immutable.
Creating Strings:
1. We can declare a String variable and directly store a String literal using assignment
operator.
String str; // declaring the string type variable
Str=”Hello java”; //assign a group of characters to it
String str = “Hello java”
In this case JVM creates an object and stores “hello java” in that object. This object is
referenced by the variable “str”.
2. We can create an object to String class by allocating memory using new Operator. This is
like creating an object to any class.
String s1 = new String ("Java");
3. We can create a String by converting the character array into strings.
char arr[ ] = { 'p','r','o',‟g‟,‟r‟,‟a‟,‟m‟};
String s2 = new String (arr);
Now the String object contains the String “program”. This means all the characters of the
array are copied into the String.
4. We can also create a String by passing array name and specifying which characters we
need:
String s3 = new String ( arr, 2, 3 );
Here starting from 2nd character a total of 3 characters are copied into String s3.
5. We can also create a string object by using another string object
String s1= ”java”;
String s2= new String(s1);
5. equals ( )
This method returns true if the two strings are same, otherwise false. This is case
sensitive.
Syntax:
boolean equals(Object str);
6. equalsIgnoreCase (String str)
Same as preceding but it performs case insensitive comparison.
Syntax:
boolean equalsIgnoreCase (String str)
Example:
Write a program to sort the given names in ascending order
class str_sort{
public static void main(String args[ ]) {
String st[ ]={"fortran","cobol","vb","Java","vc","basic"};
int i,j;
System.out.println("Before Sorting ");
for( i=0;i<st.length;i++)
System.out.println(st[i]);
System.out.print("\n"+"\n");
for(i=0;i<st.length;i++)
for(j=i+1;j<=st.length-1;j++)
if(st[i].compareTo(st[j])>0) {
String t=st[i];
st[i]=st[j];
st[j]=t;
}
System.out.println("After Sorting");
for(i=0;i<st.length;i++)
System.out.println(st[i]);
}}
Output:
Before Sorting
fortran cobol vb Java vc basic
After Sorting
Java basic cobol fortran vb vc
Vectors
Explain about Vectors in java?
Vector is a dynamic array that can hold objects of any type and any number. The
objects do not have to be homogeneous. Arrays can be easily implemented as vectors.
This class is defined in java.util package. Vectors are created like arrays follows:
Vector v1 = new Vector( ) // declaring without size
Vector v2 = new Vector(3)//declaring with size of 3 elements
A vector without size can accommodate an unknown number of items. Even when a
size specified, this can be overlooked and different no of items can be put into the
Vector. Vectors possess a number of advantages over arrays
It is convenient to use vector to store objects.
A vector can be used to store a list of objects that may vary in size.
We can add and delete objects from the list as and when required.
The major limitations in using vectors are that we can‟t directly store simple data type
in a vector. We can only store objects.
Vector class Methods:
The vector class defines number methods that can be used to manipulate the vectors created.
1. addElement(object item) : This methods adds an item specified to the list at the end.
2. elementAt( int index) : This method gives the name of the item at index place.
3. Size( ) : Gives no of elements in the list present.
4. removeElementAt(int index) : Removes the item present at the index position.
5. removeElement(item) : Removes the specified item from the list.
6. copyInto(array) : Copies the entire list into another array.
7. insertElementAt (item,n) : inserts an item in a specified location in the list.
Example:
Wite a program to read some names into the vector and print them back
import java.util.*;
class vector_ex{
public static void main(String args[ ]){
Vector v= new Vector( );
Scanner sc = new Scanner(System.in);
int i;
System.out.println("enter 3 names ");
for(i=0;i<3 ;i++)
v.addElement(sc.next( ));
System.out.println("The names are ");
for(i=0;i<3 ;i++)
System.out.println(v.elementAt(i));
}}
Output:
enter 3 names
hari giri siri
The names are
hari giri siri
Wrapper Classes
What is a Wrapper Class and explain its methods?
Wrapper Classes are used to convert primitive data types into objects. A wrapper class
is a class whose object wraps the primitive data type. Wrapper classes are available in
java.lang package. Different applications on internet send data or receive data in the
form of objects.
Primitive Data type Wrapper class
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
Character Class:
The Character class wraps a value of the primitive type char in an object. An object of
type character contains a single field whose type is char. We can create Character
class object as:
Character obj = new Character (ch); // where ch is a character.
Byte Class:
The Byte class wraps a value of primitive type 'byte' in an object. An object of type
Byte contains a single field whose type is byte. Constructors:
Byte (byte num)
Byte (String str)
Short Class:
Short class wraps a value of primitive data type 'short' in its object. Short class object
contains a short type field that stores a short number. Constructors are
Short (short num)
Short (String str)
Integer Class:
Integer class wraps a value of the primitive type 'int' in an object. An object of type
Integer contains a single field whose type is int. Constructors are
Integer (int num)
Integer (String str)
Float Class:
Float class wraps a value of primitive type float in an object. An object of type float
contains a single field whose type is float. Constructors are
Float (float num)
Float (String str)
Long Class:
The Long class contains a primitive long type data. The object of Long class contains
a field where we can store a long value. Constructors are
Long (long num)
Long(String str):
Boolean class:
The Boolean class object contains a primitive 'boolean' type data. The object of Boolean class
contains a field where we can store a boolean value. Constructors are
Boolean (true);
Boolean (str);
Double Class:
Double class wraps a value of primitive type Double in an Object. Constructors are
Double (double num)
Double (String str)
Wrapper class methods:
The wrapper classes have a number of unique methods for handling primitive data
types and objects.
1. Converting primitive number to Object number
Integer intobj = new Integer(10);
Float fl_obj= new Float(10.5f);
Double dou_obj = new Double(10.5);
2. Converting Object numbers to Primitive numbers
int i = intobj . intValue( );
float f1= fl_obj . floatValue( );
Interfaces
What is an interface and how it is implemented, explain with an example?
An interface is basically a kind of class. Using interface, you can specify what a class must
do, but not how it does it. Interfaces are syntactically similar to classes, but they lack instance
variables, and their methods are declared without any body. An interface is defined much like
a class. This is the general form of an interface:
access interface name {
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
}
Example:
interface Shape
{
void area ( );
void volume ( );
static final double pi = 3.14;
}
Implementing Interfaces
Once it is defined, any number of classes can implement an interface. Also, one class can
implement any number of interfaces.
If a class implements more than one interface, the interfaces are separated with a comma. The
methods that implement an interface must be declared public. Also, the type signature of the
implementing method must match exactly the type signature specified in the interface
definition.
Example:
Write an example program for interface
interface Shape {
void area ( );
double pi = 3.14;
}
class InterfaceDemo{
public static void main (String args[ ]){
Circle ob1 = new Circle (10.2);
ob1.area ( );
Rectangle ob2 = new Rectangle (12.6, 23.55);
ob2.area ( );
}
}
Output:
Area of a circle is : 326.68559999999997
Area of a Rectangle is : 296.73
Classes Interfaces
Classes have instances as variables and Interfaces have instances as abstract methods
methods with body and final constants variables.
Inheritance goes with extends keyword Inheritance goes with implements keywords.
The variables can have any access specifier. The Variables should be public, static, final
Multiple inheritance is not possible It is possible
Classes are created by putting the keyword Interfaces are created by putting the keyword
class prior to class_name. interface prior to interface_name
Classes contain any type of methods. Classes Interfaces contain abstract methods.
may or may not provide the abstractions. Interfaces are exhibit the fully abstractions
Interfaces
An interface is a specification of method prototypes.
An interface contains zero or more abstract methods. All the methods of interface are
public, abstract by default.
An interface may contain variables which are by default public static final.
Once an interface is written any third party vendor can implement it.
All the methods of the interface should be implemented in its implementation classes.
If any one of the method is not implemented, then that implementation class should be
declared as abstract.
We cannot create an object to an interface. We can create a reference variable to an
interface.
An interface cannot implement another interface. An interface can extend another
interface. A class can implement multiple interfaces.