Unit Ii
Unit Ii
Inheritance :
Inheritance is a mechanism in which one class can acquire the properties of another
class. Here, one object acquires all the properties and behaviors of parent object.
The idea behind inheritance is that you can create new class from existing classes .So
that new class will inherit or reuse methods and variables of its parent class and you can add new
methods and variables.
Syntax of Inheritance:
----
----
// members
The keyword extends indicates that you are making a new class that derives from
an existing class. In the terminology of java , a class that is inherited is called a
superclass. The new class is called a subclass.
Ex :
class Employee
{
float salary=40000;
}
Types of Inheritance:
1. Single inheritance
2. Multi level inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
1. Single Inheritance :
when a single derived class is created from a single base class then
the inheritance is called as single inheritance.
3. Heirarchical Inheritance:
when more than one derived class are created from a single base
class,then that inheritance is called as heirarchical inheritance.
4.Multiple inheritance:
when a derived class is created from more than one base class then
that inheritance is called as multiple inheritance.But multiple inheritance is
not supported by java using classes and can be done using interfaces.
5.Hybrid Inheritance:
class A
{
int i;
void showi()
{
System.out.println("i = " + i);
}
}
class B extends A
{
int j;
void showj()
{
System.out.println("j = " +j);
}
void sum()
{
System.out.println("sum = " + (i+j));
}
class Inheritance
{
public static void main(String args[])
{
A obj1=new A();
B obj2=new B();
obj1.i=10;
obj2.i=30;
obj2.j=20;
obj1.showi();
obj2.showj();
obj2.sum();
}
}
output :
output :
class B extends A
{
int b;
void showb()
{
System.out.println("b =" +b);
}
void sum()
{
System.out.println("sum = " + (a+b));
}
}
class C extends A
{
int c;
void showc()
{
System.out.println("c = " +c);
}
void sum()
{
System.out.println("sum = " + (a+c));
}
}
class HInheritance
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
obj1.a=10;
obj1.b=20;
obj1.showa();
obj1.showb();
obj1.sum();
obj2.a=30;
obj2.c=40;
obj2.showa();
obj2.showc();
obj2.sum();
}
}
output:
Super Keyword:
if super class and sub class has variable with the same name
then super is used to point the super class member.
syntax : super.member
Ex :
class A
{
int i=10;
}
class B extends A
{
int i=20;
void display()
{
System.out.println("value of sub class i = " + i);
System.out.println("value of superclass i = "+super.i);
}
}
class SuperDemo
{
public static void main(String args[])
{
B obj1= new B();
obj1.display();
}
}
Output :
Ex :
class Person
{
void message()
{
System.out.println("Base class message method");
}
}
class Student extends Person
{
void message()
{
System.out.println("derived class message method");
}
void display()
{
message();
super.message();
}
}
class SuperDemo1
{
public static void main(String args[])
{
Student obj1= new Student();
obj1.display();
}
}
output :
The super keyword can also be used to invoke the parent class
constructor as given below.
Ex :
class A
{
A()
{
System.out.println("Base class constructor");
}
}
class B extends A
{
B()
{
super();
System.out.println("derived class constructor");
}
}
class SuperDemo2
{
public static void main(String args[])
{
B obj1 =new B();
}
}
output :
Note :
final keyword:
Ex :
class Bike
{
final void run()
{
System.out.println(“running”);
}
}
class Honda extends Bike
{
void run() //error, final methods can’t be overridden
{
System.out.println(“running safely”);
}
}
(iii)final class :
java class with final keyword is called final class in java.Final class is
complete in nature and cannot be inherited.
{
void run()
{
System.out.println(“running”);
}
}
class Honda extends Bike // error cannot inherit
{
void run()
{
System.out.println(“running safely”);
}
}
(ii)
Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and
type signature as a method in its super class, then the method in the subclass is
said to override the method in the super class.
when an overridden method is called from with in its subclass, it will always
refer to the version of that method defined by the subclass. super class method
version will be hidden.
Ex:
class Bank
{
int getRateofInterest()
{
return 0;
}
}
Ex :
parent p=new parent();
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
}
class Cat extends Animal
{
void eat()
{
System.out.println("eating rat...");
}
}
class Lion extends Animal
{
void eat()
{
System.out.println("eating meat...");
}
}
class RunTimePolymorphism1
{
public static void main(String[] args)
{
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}
}
1.writing 2 or more methods with the same 1. writing 2 or more methods with the same
name but with different signature is called name and same signature is called method
method Overloading Overriding
2.Method overloading is done in the same class 2.Method overriding is done in super and sub
classes
3. In method overloading method return type 3. In method overriding method return types
can be same or different. should be same.
4.JVM decides which method is called 4. JVM decides which method is called
depending on the difference in method depending on the object used to call the
signatures at compile time method at run time.
5.This is called as compile time polymorphism 5.This is called as Run time polymorphism
6.same method is defined to perform different 6.In method overriding the subclass method
tasks in method overloading. overrides (replaces) super class method.
abstract method and abstract class:
abstract method :
An abstract method is a method without method body. It is a
method which must be overridden by its subclass.
sometimes we want to define a super class that declares the
structure of a given abstraction without providing a complete
implementation of every method. That is we want to create a super class
that only defines a generalized form that will be shared by all of its sub
classes, leaving it to each subclass to fill in the details.
Syntax :
abstract returntype methodname(parameter list);
abstract class :
Any class that contains one or more abstract methods must also be
declared as abstract and it is called abstract class.
syntax:
abstract class classname
{
--------
--------
abstract returntype methodname(parameterlist);
}
points to remember:
1.we can not create objects to an abstract class.
2. we can not declare abstract constructors.
3. we can not declare abstract static methods.
4. abstract classes can have constructors, member variables and normal
methods in addition to abstract methods.
5.all the abstract methods of a abstract class should be implemented in
its sub class.
6.if any abstract method is not implemented then that subclass should be
declared as abstract.
In this case we can’t create an object to the sub class.
7. we can’t declare a class as both abstract and final.
when to use :
abstract methods are usually declared when two or more subclasses
are expected to do a similar thing in different ways through different
implementations.
Ex : Write a java program to implement abstract class to calculate
areas of different shapes.
abstract class A
{ abstract void squareArea(int a);
abstract void rectangleArea(int l, int b);
abstract void circleArea(float r);
}
class B extends A
{
void squareArea(int a)
{
System.out.println("Area of square = " + (a*a));
}
void rectangleArea(int l,int b)
{
System.out.println("Area of rectangle= " + (l*b));
}
void circleArea(float r)
{
System.out.println("area of circle = " +(3.14*r*r));
}
}
class AbstractDemo
{
public static void main(String args[])
{
B obj= new B();
obj.squareArea(5);
obj.rectangleArea(5,10);
obj.circleArea(2.5f);
}
}
packages :
package : A package is a group of similar types of classes, interfaces and sub-
packages. A package is a directory for holding java files. A package can be defined
as a collection used for grouping a variety of classes and interfaces based on their
functionality.
1. built-in packages
2. user-defined package.
Built-in packages :
java has many predefined packages which can be used in programs and are
given by sun micro systems. Some of them are java, lang, awt, javax, swing, net,
io, util, sql etc.
java.lang : consists of primary classes and interfaces essential for developing a
basic java program.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any directory
name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the package
within the same directory, you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
class B
{
public static void main(String args[])
{
A obj = new A();
10. obj.msg();
11. }
12. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
package pack;
public class A{
public void msg()
{
System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;
class B
{
public static void main(String args[])
{
A obj = new A();
10. obj.msg();
11. }
12. }
Output:Hello
It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
If you import a package, all the classes and interface of that package will be imported excluding the classes and interfa
subpackages. Hence, you need to import the subpackage as well.
Note: Sequence of the program must be package then import then class.
Ex 2 :
package mypack;
class Addition
{
void sum(int a,int b)
{
System.out.println(“ sum = “ + (a+b));
}
}
save : Addition.java
compile: javac -d . Addition.java
----------------------------------
package mypack;
class Subtraction
{
void diff(int a,int b)
{
System.out.println(“Difference =” + (a-b));
}
}
save : Subtraction.java
compile : javac -d . Subtraction.java
-------------------------
package mypack;
import mypack.*;
class PackDemo
{
public static void main(String args[])
{
Addition a = new Addition();
Subtraction b = new Subtraction();
a.sum(10,20);
b.diff(10,20);
}
}
save : PackDemo.java
Compile : javac -d . PackDemo.java
Execute : java mypack.PackDemo
syntax :
package rootpackagename.subpackagename;
using packages :
To import all the classes in a package, we can use wildcard
notation.
import java.awt.*;
to import a specific class we can specify the classname as
import java.awt.Rectangle;
classes in a package java.lang are automatically imported . For all other
classes , you must supply an import statement.
Example :
Recursive program to calculate factorial in a package.
package p1;
public class RecFactorial
{
public long fact(int n)
{
if(n==0)
return 1;
else
return(n*fact(n-1));
}
}
save : RecFactorial.java
compile : javac -d . RecFactorial.java
-------------------------------------------
package p2;
import p1.*;
class Test
{
public static void main(String args[])
{
RecFactorial obj = new RecFactorial();
System.out.println("factorial = " +obj.fact(5));
}
}
save : Test.java
compile :javac -d . Test.java
execute : java
Static :
static member can be accessed independently without an object. When a member is
declared as static, it can be accessed before any objects of its class are created, and without
reference to any object.
The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
1. static variables :
class / static variables declaration is preceeded with the keyword static. They are
declared inside a class but outside a method.The most important point about static variables is
that there exists only a single copy of static variables per class. All objects of the class share this
variables. By default, static variables are initialized to their default values according to their
respective types.
java does not allow global variables . The closest thing we can get to a global variable in
java is to make the instance variable in the class static.
When a variable is declared with the keyword static ,it is called as a class variable.
Example :
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display the values
void display ()
{
System.out.println(“rollno= “ + rollno);
System.out.println(“name “ = +name);
System.out.println(“college =” +college);
}
}
//Test class to show the values of objects
public class TestStaticVariable1
{
public static void main(String args[])
{
Student s1 = new Student(501,"Kranthi");
Student s2 = new Student(1201,"Anand");
s1.display();
s2.display();
}
}
Note : As we have mentioned above, static variables will get the memory only once, if any object changes
the values of the static variable, it will remain its value.
Ex :
//Java Program to illustrate the use of static variable which
//is shared with all objects.
class CounterEx
{
static int count=0;//will get memory only once and retain its value
CounterEx()
{
count++;//incrementing the value of static variable
System.out.println(count);
}
If you apply static keyword with any method, it is known as static method.
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
There are 3 main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. They cannot refer to this or super in any way.
3. They cannot access non-static data.
Ex1 :
class A{
int a=40;//non static
Ex3: static method that access data member and can change the value of it.
class Student
{
int rollno;
String name;
static String college= "MIC";
static void change()
{
college="MIC College";
}
Student(int r, String n)
{
rollno=r;
name=n;
}
void display()
{
System.out.println(rollno + " " + name +" "+ college);
}
public static void main(String args[])
{
Student.change();
Student s1= new Student(501,"aaa");
Student s2= new Student(502,"bbb");
s1.display();
s2.display();
}
}
output :
501 aaa MIC College
502 bbb MIC College
Note :
Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of extra
memory allocation.
class A
{
static i;
static
{
System.out.println("static block is invoked");
i=10;
}
public static void main(String args[])
{
System.out.println("Now main method is invoked");
System.out.println(A.i);
}
}
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not
possible to execute a Java class without the main method.
this keyword:-
“this” can be used inside any method to refer to the current object. “this” is
always a reference to the object on which the method was invoked.
program to illustrate the use of this to refer current class instance variable :
class Student1
{
int rollno;
String name;
Student1(int rollno, String name)
{
this.rollno= rollno;
this.name=name;
}
void show()
{
System.out.println(rollno + " " +name);
}
}
class ThisEx
{
public static void main(String args[])
{
Student1 s= new Student1(1,"aaa");
s.show();
}
}
2. this : To invoke current class method:
“this” can be used to invoke current class method. If you don’t use the
this keyword , compiler automatically adds this keyword while invoking
the method.
Write a program to illustrate the use of this to invoke current class method
class A
{
void method1()
{
System.out.println("hello method 1");
}
void method2()
{
System.out.println("hello method 2");
this.method1();
}
}
class ThisEx1
{
public static void main(String args[])
{
A obj = new A();
obj.method2();
}
}
3. this : To invoke current class constructor
the this() constructor call can be used to invoke the current class
constructor. It is used to reuse the constructor.
We can call default constructor from parameterized constructor.
Write a program to illustrate the use of thisto invoke current class constructor
class A
{
A()
{
System.out.println("hello A");
}
A(int x)
{
this();
System.out.println(x);
}
}
class ThisEx2
{
public static void main(String args[])
{
A obj = new A(10);
}
}
Arrays
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
we can access a specific element in the array by specifying its index within square brackets.
Advantages :
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
Ex : datatype arrayname[];
arrayname=new datatype[size];
marks[0]=60;
marks[1]=70;
marks[2]=90;
//initializing
marks[3]=50;
marks[4]=40
we can pass the values from keyboard to the array by using a loop.
for(int i=0;i<5;i++)
{
marks[i]=s.nextInt();
}
System.out.println(marks[i]);
Ex1 : write a java program to initialize array and display the array elements.
class ArrayEx1
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
import java.util.Scanner;
class BubbleSort
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int i,n,j,temp;
int a[]= new int[20];
System.out.println("enter n value");
n = s.nextInt();
System.out.println("Enter elements in sorted order");
for(i=0;i<n;i++)
{
System.out.println("enter a[" + i + "] =");
a[i]=s.nextInt();
}
for(i=1;i<=n-1;i++)
{
for(j=0;j<=n-2;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("sorted elements are");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
int i,temp,key,low,high,mid,flag=0;
int a[]= new int[20];
System.out.println("enter n value");
int n = s.nextInt();
System.out.println("Enter elements in sorted order");
for(i=0;i<n;i++)
{
System.out.println("enter a[" + i + "] =");
a[i]=s.nextInt();
}
System.out.println("Enter element to search for");
key=s.nextInt();
low=0;
high=n-1;
while(low<=high)
{
mid = (low+high)/2;
if(key == a[mid])
{
System.out.println("key found at " + (mid+1) + " location");
flag=1;
break;
}
else if(key < a[mid])
high = mid - 1;
else
low = mid + 1;
}
if(flag==0)
System.out.println("key not found");
}
}
Ex4:Write a JAVA program to sort for an element in a given list of elements
using merge sort.
import java.util.Scanner;
class MergeSortEx
{
static void mergesort(int a[],int low, int high)
{
if(low<high)
{
int mid=(low + high)/2;
mergesort(a,low,mid);
mergesort(a,mid+1,high);
merge(a,low,mid,high);
}
else
return;
}
static void merge(int a[],int low, int mid, int high)
{
int b[]=new int[a.length];
int i,j,k;
i=low;
j=mid+1;
k=0;
while(i<=mid && j <= high)
{
if(a[i]<a[j])
b[k++]=a[i++];
else
b[k++]=a[j++];
}
while(i<=mid)
b[k++]=a[i++];
while(j<=high)
b[k++]=a[j++];
for(i=low,j=0;i<=high;i++,j++)
a[i]=b[j];
}
Note :
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
//printing 2D array
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
}
}
}
Command line arguments
These are the parameters that are passed into a program while executing.
These arguments are stored as string data type in a string array args[] of main()
method.
The first command line argument is stored as args[0] and second as args[1]
and so on.
Ex:
class CommandLine
{
public static void main(String args[])
{
for(int i=0;I < args.length; i++)
System.out.println(args[i]);
}
}
ouput:
d:\> java CommandLine CSE IT MECH
CSE
IT
MECH
Ex2 : write a program which computes sum of 2 numbers by accepting the data
from command prompt
class Sum
{
public static void main(String args[])
{
int n= args.length;
System.out.println(“No of arguments = “ + n);
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z = x + y;
System.out.println(“sum =” + z);
}
}
output:
d:\> javac Sum.java
Ex3 : write a program which checks whether given no is even or odd by taking
data from keyboard.
class EvenOdd
{
public static void main(String args[])
{
int n = Integer.parseInt(args[0]);
if(n%2==0)
System.out.println( n + " is even");
else
System.out.println(n + " is odd");
}
}
output : d:\> javac EvenOdd.java
d:\> java EvenOdd 5
5 is odd
Nested classes :
In java, it is possible to define a class within another class, such classes are
known as nested classes.
1) The scope of the nested class(inner class) is bounded by the scope of its
enclosing class(outer class).
2) Additionally, it can access all the members of outer class including private
data members and methods. However, reverse is not true i.e the enclosing
outer class does not have access to the nested class.
3) A nested class is also a member of its enclosing class.
4) As a member of its enclosing class, a nested class can be declared
private,public, protected , default.
Syntax :
class Outer
{
----
class Inner
{
----
----
}
----
}
Types of nested classes
1.static nested class
2. Inner class
Nested classes
Ex:
class Outer
int y=20;
class Inner
void display()
System.out.println(“x=”+x +”y=”+y+”z=”+z);
of outer class.
}}
class OuterDemo
{
public static void main(String args[])
{
Outer outerobj= new Outer();
Outer.Inner innerobj=outerobj.new Inner();
innerobj.display();
}
}
2.Anonymous inner classes : are the classes with no name and for them only a
single object is created. It should be used if you have to override method of a
class or interface. Anonymous inner classes are useful in writing implementation
classes for listened interfaces in graphics programming.
2.Interface
Ex: