Syllabus:: Unit-3: Classes, Inheritance, Exceptions, Packages and Interfaces
Syllabus:: Unit-3: Classes, Inheritance, Exceptions, Packages and Interfaces
Syllabus:
Beautiful thought: “You have to grow from the inside out. None can teach you, none
can make you spiritual. There is no other teacher but your own soul.” ― Swami
Vivekananda
1. CLASSES:
Definition
A class is a template for an object, and defines the data fields and methods
of the object. The class methods provide access to manipulate the data fields. The
Example Program:
class RectangleArea
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(); //object creation
rect1.getdata(10,20); //calling methods using object with dot(.)
int area1=rect1.rectArea();
System.out.println("Area1="+area1);
}
}
class. Each object occupies some memory to hold its instance variables (i.e.
its state).
The above two statements declares an object rect1 and rect2 is of type
memory for an object and returns a refernce to it.in java all class objects
The Constructors:
All classes have constructors, whether you define one or not, because
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Parameterized Constructor:
same way that they are added to a method: just declare them
Example:
// A simple constructor.
class MyClass
{
int x;
class ConsDemo
{
public static void main(String args[])
{
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
10 20
static keyword
static variable
class Counter
{
int count=0;//will get memory when instance is created
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
As we have mentioned above, static variable will get the memory only
once, if any object changes the value of the static variable, it will retain its
value.
class Counter
{
static int count=0;//will get memory only once and retain its value
Counter()
{
count++;
System.out.println(count);
}
}
Class MyPgm
{
public static void main(String args[])
{
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}
}
Output:1
2
3
static method
If you apply static keyword with any method, it is known as static method
class Calculate
{
static int cube(int x)
{
return x*x*x;
}
Class MyPgm
{
public static void main(String args[])
{
//calling a method directly with class (without creation of object)
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125
this keyword
Output: 0 null
0 null
In the above example, parameter (formal arguments) and instance variables are
same that is why we are using this keyword to distinguish between local variable and
instance variable.
Inner class
It has access to all variables and methods of Outer class and may refer to
them directly. But the reverse is not true, that is, Outer class cannot
directly access members of Inner class.
One more important thing to notice about an Inner class is that it can be
created only within the scope of Outer class. Java compiler generates an
error if any code outside Outer class attempts to instantiate Inner class.
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output:
Inside inner
Garbage Collection
longer needed and the memories occupied by the object are released. This
No, the Garbage Collection cannot be forced explicitly. We may request JVM for
garbage collection by calling System.gc() method. But this does not guarantee that
3. Increases memory efficiency and decreases the chances for memory leak.
finalize() method
Sometime an object will need to perform some specific task before it is destroyed
such as closing an open connection or releasing any resources held. To handle such
thread before collecting object. It’s the last chance for any object to perform
cleanup utility.
//finalize-code
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does
not guarantee that JVM will perform the garbage collection. It only requests the
JVM for garbage collection. This method is present in System and Runtime class.
Output :
Garbage Collected
Inheritance:
purpose.
The derived class is called as child class or the subclass or we can say
the extended class and the class from which we are deriving the
Types of Inheritance
2. Multilevel Inheritance
When a subclass is derived simply from its parent class then this
inheritance there is only a sub class and its parent class. It is also
Example
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
void display()
{
System.out.println("y"); //inherited “y” from class A
}
}
The syntax for creating a subclass is simple. At the beginning of your class
declaration, use the extends keyword, followed by the name of the class to
inherit from:
class A
{
Multilevel Inheritance
The derived class is called the subclass or child class for it's parent
class and this parent class works as the child class for it's just above
( parent ) class.
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
void Showb()
{
System.out.println("B");
}
}
class C extends B
{
void display()
{
System.out.println("C");
}
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
}
OUTPUT
5
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a
single class is known as multiple inheritance. Java does not support multiple
interface.
Here you can derive a class from any number of base classes. Deriving a
class from more than one direct base class is called multiple inheritance.
super keyword
The super is java keyword. As the name suggest super is used to access the
The first use of keyword super is to access the hidden data variables of the
Example: Suppose class A is the super class that has two instance variables
as int a and float b. class B is the subclass that also contains its own data members
named a and b. then we can access the super class (class A) variables a and b inside
super.member;
subclass hides the members of a super class having the same name. The
Example:
class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
}
class B extends A
{
int a;
float b;
B( int p, float q)
{
a = p;
super.b = q;
}
void Show()
{
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
}
class Mypgm
{
public static void main(String[] args)
{
B subobj = new B(1, 5);
subobj.Show();
}
}
OUTPUT
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Use of super to call super class constructor: The second use of the keyword
super in java is to call super class constructor in the subclass. This functionality can
super(param-list);
Here parameter list is the list of the parameter requires by the constructor
in the super class. super must be the first statement executed inside a
pass the empty parameter list. The following program illustrates the use of
Example:
class A
{
int a;
int b;
int c;
A(int p, int q, int r)
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int l, int m, int n, int o)
{
super(l,m,n);
d=o;
}
void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
class Mypgm
{
public static void main(String args[])
{
B b = new B(4,3,8,7);
b.Show();
}
}
OUTPUT
a=4
b=3
c=8
d=7
Method Overriding
method.
extend the super class. In the example class B is the sub class and class A
Example:
class A
{
int i;
A(int a, int b)
{
i = a+b;
}
void add()
{
System.out.println("Sum of a and b is: " + i);
}
}
class B extends A
{
int j;
B(int a, int b, int c)
{
super(a, b);
j = a+b+c;
}
void add()
{
super.add();
System.out.println("Sum of a, b and c is: " + j);
}
}
class MethodOverriding
{
public static void main(String args[])
{
B b = new B(10, 20, 30);
b.add();
}
}
OUTPUT
Sum of a and b is: 30
Sum of a, b and c is: 60
Method Overloading
Two or more methods have the same names but different argument lists.
The arguments may differ in type or number, or both. However, the return
Example:
class MethodOverloading
{
int add( int a,int b)
{
return(a+b);
}
float add(float a,float b)
{
return(a+b);
}
double add( int a, double b,double c)
{
return(a+b+c);
}
}
class MainClass
{
public static void main( String arr[] )
{
MethodOverloading mobj = new MethodOverloading ();
System.out.println(mobj.add(50,60));
System.out.println(mobj.add(3.5f,2.5f));
System.out.println(mobj.add(10,30.5,10.5));
}
}
OUTPUT
110
6.0
51.0
Abstract Class
Example Program:
}
double area()
{
System.out.println("Traingle Area");
return dim1*dim2/2;
}
}
class MyPgm
{
public static void main(String args[])
{
The final keyword in java is used to restrict the user. The final keyword can be
used in many context. Final can be:
1. variable
2. method
3. class
1) final variable: If you make any variable as final, you cannot change the value of
final variable(It will be constant).
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
}
Class MyPgm
{
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Output:Compile Time Error
2) final method: If you make any method as final, you cannot override it.
Example:
class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
}
Class MyPgm
{
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
3) final class:If you make any class as final, you cannot extend it.
Example:
Class MyPgm
{
Exception handling:
Introduction
execution and disrupts the normal flow of instructions. The abnormal event can be
programming language.
Concepts of Exceptions
program.
Example: If you divide a number by zero or open a file that does not exist, an
exception is raised.
In java, exceptions can be handled either by the java run-time system or by a user-
The unexpected situations that may occur during program execution are:
1. try:
2. catch.
3. throw.
4. throws.
5. finally.
Exceptions are handled using a try-catch-finally construct, which has the Syntax.
try
{
<code>
}
catch (<exception type1> <parameter1>)
{
// 0 or more<statements>
}
finally
{
// finally block<statements>
}
1. try Block: The java code that you think may produce an exception is placed
within a try block for a suitable catch block to handle the error.
If no exception occurs the execution proceeds with the finally block else it
will look for the matching catch block to handle the error.
Again if the matching catch handler is not found execution proceeds with
the finally block and the default exception handler throws an exception.
2. catch Block: Exceptions thrown during execution of the try block can be caught
and handled in a catch block. On exit from a catch block, normal execution
continues and the finally block is executed (Though the catch block throws an
exception).
3. finally Block: A finally block is always executed, regardless of the cause of exit
from the try block, or whether any catch block was executed. Generally finally
block is used for freeing resources, cleaning up, closing connections etc.
Example:
The following is an array is declared with 2 elements. Then the code tries to access
A try block can be followed by multiple catch blocks. The syntax for multiple catch
try
{
// code
}
catch(ExceptionType1 e1)
{
//Catch block
}
catch(ExceptionType2 e2)
{
//Catch block
}
catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any
statements.
class Multi_Catch
{
public static void main (String args [])
{
try
{
int a=args.length;
System.out.println(“a=”+a);
int b=50/a;
int c[]={1}
}
catch (ArithmeticException e)
{
System.out.println ("Division by zero");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println (" array index out of bound");
}
}
}
OUTPUT
Division by zero
array index out of bound
Just like the multiple catch blocks, we can also have multiple try blocks.
These try blocks may be written independently or we can nest the try blocks
within each other, i.e., keep one try-catch block within another try-block.
Syntax
try
{
// statements
// statements
try
{
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
// statements
// statements
}
catch (<exception_two> obj)
{
// statements
}
Consider the following example in which you are accepting two numbers from
the command line. After that, the command line arguments, which are in the
If the numbers were not received properly in a number format, then during
goes to the next try block. Inside this second try-catch block the first
number is divided by the second number, and during the calculation if there
Example
class Nested_Try
{
public static void main (String args [ ] )
{
try
{
int a = Integer.parseInt (args [0]);
int b = Integer.parseInt (args [1]);
int quot = 0;
try
{
quot = a / b;
System.out.println(quot);
}
catch (ArithmeticException e)
{
System.out.println("divide by zero");
}
}
catch (NumberFormatException e)
{
System.out.println ("Incorrect argument type");
}
}
}
The output of the program is: If the arguments are entered properly in the
command prompt like:
OUTPUT
java Nested_Try 2 4 6
4
OUTPUT
java Nested_Try 2 4 aa
Incorrect argument type
OUTPUT
java Nested_Try 2 4 0
divide by zero
throw Keyword
new NullPointerException("test");
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught");
}
}
public static void main(String args[])
{
avg();
}
}
In the above example the avg() method throw an instance of ArithmeticException,
which is successfully handled using the catch statement.
throws Keyword
Any method capable of causing exceptions must list all the exceptions
possible during its execution, so that anyone calling that method gets a prior
knowledge about which exceptions to handle. A method can do so by using
the throws keyword.
Syntax :
NOTE : It is necessary for all exceptions, except the exceptions of type Error and
RuntimeException, or any of their subclass.
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
finally
The finally clause is written with the try-catch statement. It is guaranteed
Syntax
try
{
// statements
}
Take a look at the following example which has a catch and a finally block.
arithmetic error like divide-by-zero. After executing the catch block the
finally is also executed and you get the output for both the blocks.
Example:
class Finally_Block
{
static void division ( )
{
try
{
int num = 34, den = 0;
int quot = num / den;
}
catch(ArithmeticException e)
{
System.out.println ("Divide by zero");
}
finally
{
System.out.println ("In the finally block");
}
}
class Mypgm
{
public static void main(String args[])
{
OUTPUT
Divide by zero
In the finally block
Java defines several exception classes inside the standard package java.lang.
The most general of these exceptions are subclasses of the standard type
automatically available.
Java defines several other types of exceptions that relate to its various class
Exception Description
Exception Description
Here you can also define your own exception classes by extending Exception.
These exception can represents specific runtime condition of course you will
have to throw them yourself, but once thrown they will behave just like
ordinary exceptions.
When you define your own exception classes, choose the ancestor carefully.
Most custom exception will be part of the official design and thus checked,
return msg;
}
}
class test
{
public static void main(String args[])
{
test t = new test();
t.dd();
}
public void add()
{
try
{
int i=0;
if( i<40)
throw new MyException();
}
catch(MyException ee1)
{
System.out.println("Result:"+ee1);
}
}
}
OUTPUT
Result: You have Passed
Chained Exception
Chained exceptions are the exceptions which occur one after another i.e.
chaining exceptions.
handling the exception, which occur one after another i.e. most of the time
exception.
chained exceptions help the programmer to know when one exception causes
another.
Throwable initCause(Throwable)
Throwable(Throwable)
Throwable(String, Throwable)
Throwable getCause()
Packages in JAVA
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
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");
}
}
There are three ways to access the package from outside the package.
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.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
//save by A.java
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();
obj.msg();
}
}
Output:Hello
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A();//using fully qualified name
obj.msg();
}
}
Output:Hello
Access Modifiers/Specifiers
1. private
2. default
3. protected
4. public
The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
Interface in java
only abstract methods in the java interface does not contain method body.
Interface fields are public, static and final by default, and methods are
There are mainly three reasons to use interface. They are given below.
As shown in the figure given below, a class extends another class, an interface
Example 1
In this example, Printable interface has only one method, its implementation is
provided in the Pgm1 class.
interface printable
{
void print();
}
class IntefacePgm1
{
public static void main(String args[])
{
Pgm1 obj = new Pgm1 ();
obj.print();
}
}
Output:
Hello
Example 2
In this example, Drawable interface has only one method. Its implementation is
And, it is used by someone else. The implementation part is hidden by the user
interface Drawable
{
void draw();
}
//Implementation: by second user
d.draw();
}
}
Output:
drawing circle
Example
interface Printable
{
void print();
}
interface Showable
{
void show();
}
Class InterfaceDemo
{
public static void main(String args[])
{
Pgm2 obj = new Pgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
Example
interface Printable
{
void print();
}
interface Showable
{
void print();
}
Output:
Hello
As you can see in the above example, Printable and Showable interface have
so there is no ambiguity.
Interface inheritance
interface Printable
{
void print();
}
Class InterfaceDemo2
{
public static void main(String args[])
{
InterfacePgm2 obj = new InterfacePgm2 ();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
}
}
class MyPgm
{
stackDemo.pop();
stackDemo.push(23);
stackDemo.push(2);
stackDemo.push(73);
stackDemo.push(21);
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
stackDemo.pop();
}
Output
Questions
13. Write a java program to find the distance between two points
whose coordinates are given. The coordinates can be 2-
dimensional or 3-dimensional (for comparing the distance
between 2D and a 3D point, the 3D point, the 3D x and y
components must be divided by z). Demonstrate method
overriding in this program. (May-2007)10 marks
14. What is an interface? Write a program to illustrate multiple
inheritance using interfaces. (Jan-2010) 8Marks
15. Explain packages in java.
16. What are access specifiers? Explain with an example.
17. With an example explain static keyword in java.
18. Why java is not support concept of multiple inheritance?
Justify with an example program.
19. Write a short note on:
1. this keyword
2. super keyword
3. final keyword
4. abstract
20. Illustrate constructors with an example program