You are on page 1of 32

Java Unit I Notes BCA V Sem Teacher name - Lucky singh

History of java
 Java language developed by company “Sun Microsystems” since merge in “Oracle Corporation” and creator is “James
Gosling” in 1991.
 Sun Microsystems started by students who are studying in standard university. These people faced the problem in their
room with electronic consumers. That means one electronic consumable remote control is not worked on another
electronic consumable.
 These people wanted to develop a common remote control ( CRC) which is controlling all the electronic consumable. So
their contacted James gosling and requested for the project.
 Sun Microsystems started by group of students out of them one person also Indian name “Vinod Khosla”. James gosling
and his team members given the project name “GREEN” started in the year 1990 and 1992.
 Common Remote Control completed in the year 1992. The CRC name is star7.
 The James Gosling team develops a new language called “OAK”. But this name is already selected by some other
company and also a tree name that was stood outside the gosling office removed as Java from java coffee.
 Java has no meaning representation of Island in Indonesia. The unofficial abbreviation is “Just another virtual analyzes
(JAVA)”.
 Java is Programming language suitable to the develop of web applications. The official version of java released in the year
as
Different type of versions of JAVA
Version name Code name
JDK 1.0 Oak
JDK 1.1 Secret code
JDK 1.2/ J2SDK 1.2 Playground
JDK 1.3/ J2SDK 1.3 Kestrel
JDK 1.4/ J2SDK 1.4 Merlin
JDK 1.5/ J2SE 1.5 Tiger (September 2004)
JDK 1.6/ JAVA SE 6.0 Mustang (December 2006)
JDK 1.7/ JAVA SE 7/ JSE7 Dolphin (July 2011)
JDK 1.8/ JAVA SE 8/ JSE8 (not available)
Java Variations
1. Java SE – Java Platform, Standard Edition or Java SE is a widely used platform for development and deployment of
portable code for desktop and server environments. Java SE uses the object-oriented Java programming language. It is
part of Java software-platform family.
2. Java EE – Java Platform, Enterprise Edition or Java EE is a widely used computing platform for enterprise software. Java
EE extends the Java platform, Standard Edition (Java SE), providing an API for object-relational mapping, distributed
and multi-tier architectures, and web services.
3. Java ME – Java Platform, Micro Edition or Java ME, is a Java platform designed for embedded systems (such as mobile
device). Target devices range from industrial controls to mobile phones (especially feature phone) and set-top boxes. It
is provides robust, flexible environment for applications running on mobile and embedded devices.
Qualities of JAVA
Sun Microsystem team analyses the three qualities which are included in this new programming language.There
are as follows:

 Simple programming language


 Tight coded programming language
 Architecture neutral programming language

1.Simple programming language: they are decided that the new programming language is simple so further it
shows the three criteria are as follows:

 Less Execution time: If the execution time of the program is less than the performance of the program
and language are increases.
 Less Memory: Program stored and take less memory because no of statements are less so program
consumes less memory then the needed memory space is less so the cost is decreases.
 Less Power Consumption: When a program or software take less memory, execute less statement so
the power is used according to program. It means power consumption is maintained so the maintenance
cost is also less.

2.Tight coded programming language: Here we need to know about the loosely coded and tight coded both
definition then we understand why java is tight coded language.

 Loosely Coded: If any programming language is taking more no. of finish section to achieve a
particular requirement then that programming language is called loosely coded programming language.
 Tight Coded: If any programming language is taking less no. of finish section to achieve a particular
requirement then that programming language is called loosely coded programming language.

3.Architecture neutral programming language: firstly you need to know architecture dependent and
architecture non dependent feature.

 Architecture dependent: If any programming language is available only one kind of device so less
demand is available, platform dependent or architecture dependent language.
 Architecture non dependent: If any programming language is available for all components or
compatible for all hardware devices then more demand is available also that programming language is
platform independent, architecture non dependent or Architecture neutral.
Features of Java

 Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Interpreted
 High Performance
 Multithreaded
 Distributed
 Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Platform Independent
Java is platform independent
Java is platform independent because it is different from other languages like C, C+
+, etc. which are compiled into platform specific machines while Java is a write
once, run anywhere language. A platform is the hardware or software environment
in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on the top of other hardware-based platforms.
It has two components:
 Runtime Environment
 API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere(WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
 No explicit pointer
 Java Programs run inside a virtual machine sandbox
Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system from
those that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.

Robust
Robust simply means strong.
Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.

Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.

High-performance
Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a compiled
language (e.g., C++). Java is an interpreted language that is why it is slower than
compiled languages, e.g., C, C++, etc.

Distributed
Java is distributed because it facilitates users to create distributed applications in
Java. RMI and EJB are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on the
internet.

Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.

Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C
and C++.
Java supports dynamic compilation and automatic memory management (garbage
collection)
Java is considered to be more dynamic than C or C++ since it is designed to adapt
to an evolving environment. Java programs can carry an extensive amount of run-
time information that can be used to verify and resolve accesses to objects at run-
time.

CONST RUCTOR

It is special method which the same name as a class name.


It is not a method it is a block of code that instantiate object.
It share same name of class name means class name and constructor name are same.
It is declare must be in public area.
When object is created constructor is automatically called according to argument.
Mainly used for initialize the object of data member.
It ca n not be inherited.but can be overloaded.
Does not have return type, can not called by object.
When we create constructor compiler automatically fire according to parameters.
If we call default constructor, and create default constructor it works if not create then compiler automatically
creates default contructor.
If call parametrize constructor or create parametrize constructor and not create default constructor then
compiler create an error, first you need to create default constructor
Type of constructor-
Default constructor
Parame trized constructor
Default constructor
These are those constructors in which we don’t have to pass any arguments.
E.g.
class A
{ A()
{ System.out.println(“This is default contructor”);
}
public static void main(String ar[])
{ A ob1=new A();
}
}output: This is default contructor
Parametrized constructor
These are those constructors in which we can pass one or more arguments and
E.g. class A
{ int a;
A()
{ System.out.println(“This is default contructor”);
}
A(int a)
{ this.a=a;
System.out.println(“This is parametrize contructor : ”+a);
}
public static void main(String ar[])
{ A ob1=new A(5);
}
}output: This is parametrize contructor : 5
Constructor overloading
All constructor have same name but different parameter, number of parameter are change.
Example:
Class A
{
Int a,b,c;
A()
{
a=0;
b=0;
c=0;
}
A(int x,int y)
{
a=x;
b=y;
}
A(int x,int y, int z)
{
a=x;
b=y;
c=z;
}
public void show()
{
System.out.println(“value of A :”+a + “ value of b = “ + “ value of c = ”+ c);
}
public static void main(String arg[])
{
A ob1=new();
A ob2=new A(5,6);
A bo3=new A(5,6,1);
}
}
Copy constructor (is not in java)
There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

By constructor

By assigning the values of one object into another

In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}

Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan

We can copy the values of one object into another by assigning the objects values to another object. In this case,
there is no need to create the constructor.

class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}

Output:

111 Karan
111 Karan
Features of Java
1. Class (1. OUTER CLASS (concrete, abstract, final), 2. INNER CLASS (local, member, anonymous))
2. Object (1. Non-static 2. Static 3. Anonymous)
3. Abstraction (via abstract class & interface)
4. Encapsulation (access spacifiers, private or public area of program)
5. Inheritance (Single, Multilevel, Hierarchical, Multiple and hybrid via interface)
6. Polymorphism (Compile Time (static/early binding), Run Time(dynamic/late binding))
CLASS
 A class is a blue print from which individual objects are created. A class can contain fields and methods to describe the
behavior of an object.
 A class is the template/blueprint that describes the behavior/state of an object.
 A class as a concept, object is the embodiment of that concept.
 You need to create a class before you can create an object.
 Used class keyword.
 A class is combination of data members and member functions.
 A class is a Compile time entity.
 Syntax:
access-spacifier class class-name
{
Private area (Data members ;)
Public area (Member functions ;)
}
 Data member must be declare in private area, data member allocate memory at run time some time in compile time.
 Member function must be declared in public area, member function allocate memory at compile time in 90% cases 10% in
run time.
 To use a class firstly we have to create the instance of a class called object.
 Types of class
1. Outer class
1.1. concreate class
1.2. abstract class
1.3. final class
2. Inner class
2.1. Local inner
2.2. Member inner class
2.3. Anonymous
1. Outer class-
1.1. Concrete class- A class is inherited as well as object created.
E.g. class A
{ int a;
public void show(int a)
{ this.a=a;
System.out.println(“Value of a = ” + a);
}
public static void main(String arg[])
{ A a=new A();
a.show(5);
}
}
1.2. Abstract class- A class is inherited but not object created.class , needs to inherit.
E.g. abstract class A
{
abstract void hello();
public void show()
{ System.out.println(" show");
}
}
class B extends A
{ public void hello()
{ System.out.println(“hello”);
}
public static void main(String arg[])
{
A ob1;
B a=new B();
a.show();
a.hello();
}
}
1.3. Final class- A class is not inherited but object created.
E.g. final class A
{ public void hi()
{ System.out.println(“hi”);
}
public void static void main(String arg[])
{ A a=new A();
a.show(5);
a.hello();
}

2. Inner class
2.1. Local inner class-
 A class is declared inside the method. Cannot invoke outside the class.
 It can’t access non-final local variable till JDK 1.7.
 After 1.8 it is possible to access the non final local variable in local inner class.
class Aaaa
{ int a;
public void show(int a)
{ this.a=a;
System.out.println("outer class metoa Value of a = " + a);
class Bbbbb
{ public void ma1()
{
System.out.println("inner class ma method");
}
}
Bbbbb b=new Bbbbb();
b.ma1();
}
public static void main(String arg[])
{ Aaaa a=new Aaaa();
a.show(5);
}
}
Output : outer class metoa Value of a = 5
inner class ma method
2.2. Member inner class-
 A class is declared inside the method.
 A non-static class that is created inside a class but outside a method.
 class TestMemberOuter1{
 private int data=30;
 class Inner{
 void msg(){System.out.println("data is "+data);}
 }
 public static void main(String args[]){
 TestMemberOuter1 obj=new TestMemberOuter1();
 TestMemberOuter1.Inner in=obj.new Inner();
 in.msg();
 }
 }

2.3. Anonymous class- A class is has no name.


 A class consists of Local variable, instance variables and class variables.

Java Anonymous inner class


Java anonymous inner class is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance of an object with certain
"extras" such as overloading methods of a class or interface, without having to actually subclass a
class.
In simple words, a class that has no name is known as an anonymous inner class in Java. It should be
used if you have to override a method of class or interface. Java Anonymous inner class can be
created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }

VARIABLES
1. Local Variable
 Variables defined inside methods, constructors or blocks are called local variables.
 The variable will be declared and initialized within the method and it will be destroyed when the method has completed.
2. Instance/Global Variable
 Instance variables are variables within a class but outside any method. These variables are instantiated
when the class is loaded.
3. Class/Static Variable
 These are variables declared with in a class, outside any method, with the static keyword.

OBJECT
 An object is a component of a program that knows how to perform certain actions and how to interact with other elements
of the program.
 Use for indicate the class that this object is of that class.
 An object is an instance of a class.
 It is run time entity.
 When we use data member or member function of one class in another class we need to create object.
 Within c lass no need to create object.
 It is two step processes,
1. First declare variable of class type E.g. First ob1,
2. Second create physical copy of object and assign it to the variable using new operator it dynamically allocates
runtime me mory for an object & returns a reference to it,
E.g. ob1=ne w First();
1. First() is con structor of First class
2. An object is I nstantiated with new keyword and class constructor.
3. Reference is t he address of the object.
 Types of object -
1. Non-static- created without static keyword.
2. Static- created with static keyword.
3. Anonymous- object is not create direct instance created with new keyword.

CONST RUCTOR
 It is special method which the same name as a class name.
 It is not a method it is a block of code that instantiate object.
 It share same name of class name means class name and constructor name are same.
 It is declare must be in public area.
 When object is created constructor is automatically called according to argument.
 Mainly used for initialize the object of data member.
 It ca n not be inherited.but can be overloaded.
 Does not have return type, can not called by object.
 When we create constructor compiler automatically fire according to parameters.
 If we call default constructor, and create default constructor it works if not create then compiler automatically creates
default contructor.
 If call parametrize constructor or create parametrize constructor and not create default constructor then compiler create an
error, first you need to create default constructor
 Type of constructor-
 Default constructor
 Parametrized constructor
Default constructor
1. These are those constructors in which we don’t have to pass any arguments.
2. E.g.
class A
{ A()
{ System.out.println(“This is default contructor”);
}
public static void main(String ar[])
{ A ob1=new A();
}
}
output: This is default contructor
Parametrized constructor
 These are those constructors in which we can pass one or more arguments and
 E.g. class A
{ int a;
A()
{ System.out.println(“This is default contructor”);
}
A(int a)
{ this.a=a;
System.out.println(“This is parametrize contructor : ”+a);
}
public static void main(String ar[])
{ A ob1=new A(5);
}
}output: This is parametrize contructor : 5

Constructor Overloading in Java

Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates
these constructors by taking into account the number of parameters in the list and their type.
Example of Constructor Overloading

class A{
int id;
String name;
int age;
A(int i,String n){
id = i;
name = n;
}
A(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}

public static void main(String args[]){


A s1 = new A(111,"Karan");
A s2 = new A(222,"Aryan",25);
s1.display();
s2.display();
}
}

Test it Now

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case.

Constructor name must be same as the class name. Method name may or may not be same as class name.

Java Copy Constructor


There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++.

There are many ways to copy the values of one object into another in java. They are:

o By constructor

o By assigning the values of one object into another

o By clone() method of Object class

In this example, we are going to copy the values of one object into another using java constructor.

class A{
int id;
String name;
A(int i,String n){
id = i;
name = n;
}

A(A s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+"
"+name);}

public static void main(String args[]){


A s1 = new A(111,"Karan");
A s2 = new A(s1);
s1.display();
s2.display();
}
}
Test it Now
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor.

class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student7(){}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Test it Now

Output:

111 Karan
111 Karan

ABSTRACTION
 Data abstraction is refers to providing only essential (important) information to the outside world without showing
background details.
 It refers to the ability to make a class abstract in OOP. It helps to reduce the complexity and also improves the
maintainability of the system.
 Abstraction focus on what the object does instead of how it does it.
 Also is used to hide certain details and only show the essential features of the object (interface).
 Java abstraction achieves using abstract class and interfaces.
1. Abstract class-
 A class which contains the abstract keyword in its declaration is known as abstract class. E.g.
abstract class class-name
{ Data member;
Non-abstract Member function;
Abstract member function;
}
 It has at least one or more than one abstract method also non-abstract methods.
 Abstract method that is declared as abstract does not have body implementation. E.g. abstract void function-name();
 Abstract class needs to be extended also its abstract methods are implemented by extended class.
 It cannot be instantiated but object is created.
Program:
abstract class Abstractexa
{ abstract void show();
public void display()
{ System.out.println("display");
}
}
class Abstractexamain extends Abstractexa
{ public void show()
{ System.out.println("show");
}
public static void main(String arg [])
{ Abstractexamain ob1=new Abstractexamain();
ob1.show();
ob1.display();
}
}
Save as: Abstractexamain.java
Compile: javac Abstractexamain.java
Run: java Abstractexamain
Output: show
display
2. Interface-
 Interface is a type of class also known as pure abstract class and we use interface keyword at the place of class keyword.
 Interface cannot be instantiated
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 It contains only undefined abstract methods. So it is not possible to create object of interface. Also variable with constant
value.
 Syntax of interface variable:
 static final type variable name= value;
 static final int var1=10;
 Syntax of interface variable:
 return-type method-name (parameter-list);
 void method1 (int a);
 In this case we create a class whose implements this interface and define all methods of an interface.
 An interface is used using implements keyword.
 If nested interface then used extends keyword, is an interface used another interface means nested interface then use
extends keyword.
Program:
interface First
{ static final int code=1001;
void display();
}
class Useinter implements First
{ public void display ()
{
System.out.println ("show");
System.out.println (code);

}
public static void main(String arg[])
{
Useinter u1=new Useinter();
u1.display();
}
}
Save as: Useinter.java
Compile: javac Useinter.java
Run: java Useinter
Output: show
1001

Difference b/w abstract class and interface

Abstract class Interface


The members of a class can be constant or The members of an interface are always declared
variables. as constant. i.e., their values are final
the class definition can contain the code for each The methods in an interface are abstract in nature,
of its methods. That is, the methods can be i.e., there is no code associated with them. It is
abstract or non-abstract. later defined by the class that implements the
interface
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public , It can only use the public speciafier.
private, or protected.

ENCAPSULATION

 It means wrapping (binding) data members (variables) and member function in single unit called class.
 The variables of a class will be hidden from other classes, and can be accessed only through the methods of their current
class it is also known as data hiding.
 It is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is
declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. Therefore
encapsulation is also referred to as data hiding.
 Data can be restricted to the outside world using access specifier (default, private, public, protected).
 To achieve encapsulation in java –
1. Declare the variables of a class as private.
2. Provide public setter and getter methods to modify and view the variables values.
Program:
public class EncapExa
{ private String name;
public void setName (String ne)
{ name = ne;
}
public String getName ()
{ return name;
}
public static void main (String rah [])
{
EncapExa ob1 = new EncapExa();
ob1.setName("Amit");
String names = ob1.getName ();
System.out.println ("Name is = "+ names);
}
}
Save as: EncapExa.java
Compile: javac EncapExa r.java
Run: java EncapExa
Output: Name is = Amit

INHERITANCE
 It is the process where one object acquires all the properties or behaviours of parent object. With the use of inheritance the
information is made manageable in a hierarchical order.
 Provides the features of reusability of code.
 One class acquires the properties of another class.
 A class whose properties are acquires by another is called base/super/parent class.
 Base class not access private data members or member functions of parent class.
 A super class variable can reference a sub class object.
E.g. Parent p=new Parent(5);
Child c=new Child();
c=p;;
 A class whose acquires the properties is called sub/derived/child
 class.
 It is a concept where one class share the structure & behavior to the another class.
 Inheritance used keyword extends that indicates you are making a new class that derives from an existing class.
 Types of inheritance
Java support three type of vinheritance-
1. Single (only one super class)
2. Multilevel (derived from a derived class)
3. Hierarchical (one super class many sub class)
In java Multiple and hybrid inheritance achieve via interface (several super classes)

SINGLE LEVEL INHERITANCE


 Only one class is parent and only one class is child.
Program
class SingleinhA
{ int a;
public void show(int a)
{ this.a = a;
System.out.println ("show in A value of a= "+a);
}
}
class SingleinhB extends SingleinhA
{ public void show1()
{ System.out.println ("show1");
}
public static void main(String args[])
{ SingleinhA ob1 = new SingleinhA();
ob1.show (5);
SingleinhB ob2 = new SingleinhB();
ob2.show (6);
ob2.show1 ();
}
}
Save as: SingleinhA.java
Compile: javac SingleinhA.java
Run: java SingleinhA
Output:
MULTI LEVEL INHERITANCE
 Collection of single level inheritance.
 Derived class is again derived by another class.
Program
class A
{ int a;
public void show(int a)
{ this.a = a;
System.out.println ("show in A value of a= "+a);
}
}
class B extends A
{ public void show1()
{ System.out.println ("show1");
}
}
class C extends B
{ public void show2()
{ System.out.println ("show2");
}
}
class Test
{ public static void main(String args[])
{ B ob2 = new B ();
ob2.show (5);
ob2.show1 ();
C ob3 = new C();
ob3.show (5);
ob3.show1 ();
ob3.show2 ();
}
}
Save as: Test.java
Compile: javac Test.java
Run: java Test
Output: show in A value of a= 5
show1
show in A value of a= 5
show1
show

HIERARCHICAL INHERITANCE
 Where one class is inherited by no of subclass
 There is only one class is super and no of classes are subclass.
Program
class Ab
{ int a;
public void show(int a)
{ this.a = a;
System.out.println ("show in A value of a= "+a);
}
}
class Bb extends Ab
{ public void show1()
{ System.out.println ("show1");
}
}
class Cb extends Ab
{ public void show2()
{ System.out.println ("show2");
}
}
class Testmultipleinheritance
{public static void main(String args[])
{ Bb ob2 = new Bb ();
ob2.show (5);
ob2.show1 ();
Cb ob3 = new Cb ();
ob3.show (5);
ob3.show2 ();
}
}Save as: Testmultipleinheritance.java
Compile: javac Testmultipleinheritance .java
Run: java Testmultipleinheritance
Output: show in A value of a= 5
show1
show in A value of a= 5
show2
MULTIPLE INHERITANCE
 Where no of classes are inherited in one base class
 Multiple inheritance is not achieve by classes.
 A new concept is introducing called interface.
 Interface is collection of abstract methods which means without body.
 All methods of an interface are abstract but no need to define abstract.
 Variable of an interface are static and final.
 Variable of an interface have constant value.
 An interface created with interface keyword.
 An interface is used by a class using implements keyword.
 If an interface used in interface used extends keyword if a class used an interface then used implements keyword.
 Interface cannot be instantiated
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
Progra interface First1
{ static final int code=1001;
void display ();
}
interface Second1 extends First1
{ static final int data=2001;
void show ();
}
interface Third1
{ static final int meta=3001;
void data ();
}
class Testinterface1 implements Second1, Third1
{ public void display ()
{ System.out.println ("display");
System.out.println (code);
}
public void show ()
{ System.out.println ("show");
System.out.println (data);
}
public void data ()
{ System.out.println ("data");
System.out.println (meta);
}
}
class Examultipleinheritance
{ public static void main(String arg[])
{ Testinterface1 t1 = new Testinterface1();
t1.display();
t1.show();
t1.data();
}
}
Save as: Examultipleinheritance.java
Compile: javac Examultipleinheritance .java
Run: java Examultipleinheritance
Output: display
1001
show
2001
data
3001
 If all methods of an interface are not defined by implementing class then create that class abstract class and extends that
class again in another class & define all methods whose are not define.
Eg.
interface Firstinf
{ static final int code=1001;
void display ();
void show();
void data();
}
abstract class Test implements Firstinf
{ public void display ()
{ System.out.println ("display");
}
public void show ()
{ System.out.println ("show");
}
}
class Exainterabs extends Test
{ public void data()
{
System.out.println("data");
}

public static void main(String arg[])


{ Exainterabs t1 = new Exainterabs();
t1.display();
t1.show();
t1.data();
}
}
Save as: Exainterabs .java
Compile: javac . Exainterabs .java
Run: java Exainterabs
Output: display
show
data
POLYMORPHISM
 It is created using two terms one is “poly” means many second “morphism” means form.
 Ability to take more than one form with single name.
 Polymorphism is the ability of an object to take on many forms.
 The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
 It is achieve by two ways-
1. Compile Time (static/early binding) achieve by Method overloading.
2. Run Time(dynamic/late binding) achieve by Method overriding.
1. Compile time Polymorphism :
 Also called static polymorphism and early binding of methods with object.
 Exist at compile time.
 No of methods with same name with different forms.
o Method Overloading
 A method with same name different signature within class.
 Its differ signature according to name and parameter list no work on return type.
Programclass CompilPly
{ int in;
String sr;
public void display()
{ System.out.println ("show 1");
}
public void display(int a)
{ in=a;
System.out.println ("show 1 "+ a);
}
public void display(String ar)
{ sr=ar;
System.out.println ("show 3 "+ ar);
}
public static void main(String ar[])
{ CompilPly p1=new CompilPly();
p1.display();
p1.display(5);
p1.display("Hello");
}
}Save as: CompilPly .java
Compile: javac . CompilPly .java
Run: java CompilPly
Output: show 1
show 2 5
show 3 Hello
2. Run time polymorphism :
 Also called dynamic(run time) polymorphism and late binding of methods with objects.
 It exist in run time.
 Java compiler does not understand which method is called at compile time,
 Only JVM decides which method is called at run time.
o Method Overriding
 When a method in a sub class 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.
 A method with same name and same signature in two class one is super class and second is sub class who’s inherited the
super class.
 When object is called the method then run time decide whose method is called parent class method or sub class method.
 By default compiler calls sub class method if you want call parent class method then use super keyword.
Program: class A11
{int i , j;
A11(int a, int b)
{ i=a;
j=b;
}
public void show()
{ System.out.println ("i and j in 1c = "+ i + " , " + j);
}
}
class B11 extends A11
{ int k;
B11(int a, int b, int c)
{ super(a,b);
k=c;
}
public void show()
{ super.show();
// save with above statement and run the comment it then run
System.out.println ("k in 2c = "+ k );
}
}
class RuntimePoly
{ public static void main(String srg[])
{ B11 ob1= new B11(1,2,3);
ob1.show();
}
}
Save as: RuntimePoly
Compile: javac RuntimePoly.java
Run: java CompilPly
Output: i and j in 1c = 1 , 2
i and j in 2c = 3
EXCEPTION HANDLING
 An exception is problem that arises during the execution of a program.
 Program processing terminates abnormally.
 If flow of program is disturbed then use exception handling.
 The purpose of exception handling mechanism is to provide a means to detect & report an “exceptional
circumstances” so that appropriate action can be taken
 There are some reasons of exception-
o A user has entered wrong data.
o A file needs to open and can not found.
o A network connection has been lost in the middle of communication.
o User error, programmer error etc.
 Types of Exception handling-
1. System define Exceptions
 Checked - On compile time besides code.javac compiler handle the exceptions.
 Some checked exceptions:
1. ClassNitFoundException,
2. IllegalAccessException.
3. NoSuchFieldException,
4. EOFException etc.
 Unchecked - On run time. JVM checked the exception.
 Some checked exceptions:
1. ArithmeticException
2. ArrayIndexOutOfBoundsException

3. User define/Custom Exceptions- created by user. Needs tp inherit Exception class, used throw keyword to throw
exception. needs to override toString() method.
4. Error- software / hardware error.

Methods of Exception class


1. printstackTrace() –Trace exception
2. String grtMessage() -- Told Reason why exception occure
3. String to String() – Whose handle or print exception

There are 5 keywords to handle Exception handling


1. try
2. catch
3. throw
4. throws
5. finally
1. try –
1. Syntax: try(){}
2. All of the program code writes in try block.
3. Try block have at least one catch block its compulsory.
4. Try is keyword, try block throw an exception to catch block.
2. catch –
1. Syntax: catch(Exception e){}
2. catch block have a object of Exception class to catch exception which is throw by try block.
3. Also we use multiple catch in our program.
3. throw –
1. Internally work throws an exception.
4. throws-
2. Used in user defined exception when explicitly throws an exception.
5. finally-
3. Syntax: finally(){}
4. it is a block which is executed defiantly and necessary.
5. If you create finally block with try block then catch block is optional to create.
Advantages of Exception Handling
1. Allows us to control the normal flow of program.
2. It throws an exception whenever a calling method takes care of that error.
3. Also gives us the scope of organizing & differentiating between different error types using a separate block of codes.
This is done with the try-catch block.
Example of System define Exception
import java.util.*;
class ExhanExa
{
public static void main(String arg[])
{ Scanner sc=new Scanner(System.in);
System.out.println("Enter first integer no. : ");
try
{ int a=sc.nextInt();
System.out.println("Enter second integer no. : ");
int b=sc.nextInt();
int c= a/b;
System.out.println("Value of : "+ c);
}
catch(Exception e)
{
System.out.println("Exception is : "+e);// here for printing e value by default called toString method
e.printstackTrace();
e.getMessage();
e.toString();
}
}
}Output : Enter first integer no. :
5
Enter second integer no. :
0
Exception is : java.lang.ArithmeticException: / by zero
Example of User define Exception
import java.util.*;
public class MyOwnException extends Exception
{ int price;
MyOwnException(int price)
{ this.price=price;
}
public String toString()
{ return "price should not -ve : "+price;
}
}
Save as: MyOwnException.java
Compile: javac MyOwnException.java
1. Our user define exception class must extends Exception class and override toString() method.
Next class :
public class client extends Exception
{ public static void main(String arg[])
{ int price=-120;
if(price<0)
{ throw new MyOwnException(price)
}
else
{ System.out.println("Your price is : "+price);
}
}
}
Save as: client.java
Compile javac client.java
Run: java client
Output: price should not -ve : -120

You might also like