Unit IV - Notes
Unit IV - Notes
Inheritance:
• Inheritance can be defined as the process where one class acquires the properties of
another class
• The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
• Inheritance represents the IS-A relationship, also known as parent-child relationship.
• Advantages of inheritance:
• Code reusability
• Used in method overriding (so runtime polymorphism can be achieved).
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class.
Example:
// A simple example of inheritance.
// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A
{
int k;
void showk()
{
System.out.println("k: "+ k);
}
void sum()
{
1
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
/* In a class hierarchy, private members remain private to their class. This program contains an
error and will not compile. */
class A
{
int i; // public by default
private int j; //Private to A
2
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
class B extends A
{
void callMe()
{
System.out.print("Hi ");
}
}
class Reference
{
public static void main(String args[])
{
A ref;
B b = new B();
ref = b;
ref.callMe();
}
}
Output: Hi
Using super
Whenever the derived class inherits the base class features, there is a possibility that
base class features are similar to derived class features and JVM gets an ambiguity. To
overcome this, super is used to refer super class properties.
The super keyword in java is a reference variable that is used to refer parent class. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:
4
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Output:
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message();//will invoke or call current class message() method
super.message();//will invoke or call parent class message() method
}
}
class SuperClassMethod
{
public static void main(String args[])
{
Faculty f=new Faculty();
f.display();
}
}
Output:
}
class SuperClassConst
{
6
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Output:
Calling Constructors:
Constructors are called in order of derivation, from super class to sub class. Further,
since super( ) must be the first statement executed in a subclass’ constructor, this order is the
same whether or not super( ) is used. If super( ) is not used, then the default constructor of
each super class will be executed. The following program illustrates when constructors are
executed:
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A
{
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingConstructor
{
public static void main(String args[])
{
7
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
C c = new C();
}
}
Output:
Method Overriding:
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the method in
the superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden.
Example:
// Method overriding.
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
// display i and j
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
8
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
k = c;
}
// display k – this overrides show() in A
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output:
class C extends B
{
9
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
void callMe()
{
System.out.println("Inside C");
}
}
class DynamicMethodDispatch
{
public static void main(String args[])
{
A a=new A();
B b = new B();
C c = new C();
A ref;
ref = a;
ref.callMe();
ref = b;
ref.callMe();
ref=c;
ref.callMe();
}
}
Output:
import java.util.*;
class Student
{
int n;
String name;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter no and Name");
n=s.nextInt();
name=s.nextLine();
}
10
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
void show()
{
System.out.println("No:"+n);
System.out.println("Name:"+name);
}
}
class ITStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class CSEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class ECEStudent extends Student
{
void read()
{
super.read();
}
void show()
{
super.show();
}
}
class MainMethod
{
public static void main(String ar[])
{
ITStudent it=new ITStudent();
CSEStudent cse=new CSEStudent();
11
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Student sref;
sref=it;
sref.read();
sref.show();
sref=cse;
sref.read();
sref.show();
sref=ece;
sref.read();
sref.show();
}
}
Abstract Class
{
System.out.println("Square :"+(x*x));
}
}
class Sub2 extends MyClass
{
void calculate(double x)
{
System.out.println("Square Root :"+Math.sqrt(x));
}
}
class Sub3 extends MyClass
{
void calculate(double x)
{
System.out.println("Cube :"+(x*x*x));
}
}
class AC
{
public static void main(String arg[])
{
Sub1 obj1=new Sub1();
Sub2 obj2=new Sub2();
Sub3 obj3=new Sub3();
obj1.calculate(20);
obj2.calculate(20);
obj3.calculate(20);
}
}
{
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo
{
public static void main(String args[])
{
B b = new B();
b.callme();
b.callmetoo();
}
}
Uses of Final:
class FinalMethod
{
public static void main(String args[])
{
Bike b= new Bike();
b.run();
14
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
}
}
Error Information:
class FinalClass
{
public static void main(String args[])
{
Bike b= new Bike();
b.run();
}
}
15
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Interfaces:
A named collection of method declarations.
A Java interface is a collection of constants and abstract methods
Since all methods in an interface are abstract, the abstract modifier is usually left off
Using interface, you can specify what a class must do, but not how it does.
Interface fields are public, static and final by default, and methods are public and abstract.
Advantages of interfaces:
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritances.
Syntax:
access_specifier interface interfae_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
//...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
16
PGMCOE,Wagholi.
Unit I V Inheritance, Packages and Interfaces
Implementing Interfaces:
• Once an interface has been defined, one or more classes can implement that interface.
• To implement an interface, include the implements clause in a class definition, and then
create the methods defined by the interface.
• The general form of a class that includes the implements clause looks like this:
class classname [extends superclass] [implements interface1 [,interface2...]] {
// class-body
}
• If a class implements more than one interface, the interfaces are separated with a
comma.
• The methods that implement an interface must be public. Also, the type signature of
implementing method must match exactly the type signature specified in interface
definition.
Example 1: Write a java program to implement interface.
interface Moveable
{
int AVG_SPEED=30;
void Move();
}
class Move implements Moveable
{
void Move(){
System .out. println ("Average speed is: "+AVG_SPEED );
}
}
class Vehicle
{
public static void main (String[] arg)
{
Move m = new Move();
m.Move();
}
}
17
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
18
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Ex:
interface Test {
void call();
}
Variables in Interfaces:
We can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values. When we
include that interface in a class (that is, when you “implement” the interface), all of those
variable names will be in scope as constants. (This is similar to using a header file in C/C++ to
create a large number of #defined constants or const declarations). If an interface contains no
methods, then any class that includes such an interface doesn’t actually implement anything. It
is as if that class were importing the constant fields into the class name space as final variables.
{
int i=100;
}
class Test implements left,right
{
public static void main(String args[])
{
System.out.println(left.i);//10 will be printed
System.out.println(right.i);//100 will be printed*/
}
}
Example: Java program to demonstrate interfaces can be extended with extend keyword.
interface Teacher
{
void display1();
}
interface Student
{
void display2();
}
interface T_S extends Teacher, Student
{
void display3();
}
class College implements T_S
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
public void display2()
{
System.out.println("Hi I am Student");
}
public void display3()
{
System.out.println("Hi I am Teacher_Student");
20
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
}
}
class Class_Interface
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
c.display3();
}
Example 2: Java program to implement interface and inheriting the properties from a class.
interface Teacher
{
void display1();
}
class Student
{
void display2()
{
System.out.println("Hi I am Student");
}
}
class College extends Student implements Teacher
{
public void display1()
{
System.out.println("Hi I am Teacher");
}
}
class Interface_Class
{
public static void main(String arh[])
{
College c=new College();
c.display1();
c.display2();
}
}
21
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Packages:
22
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
23
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
package pack;
public class Subtraction
{
int x,y;
public Subtraction(int a, int b)
{
x=a;
y=b;
}
public void diff()
{
System.out.println("Difference :"+(x-y));
}
}
import pack.Addition;
import pack.Subtraction;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
3. import package.*;
import pack.*;
class UseofPack
{
public static void main(String arg[])
{
Addition a=new Addition(10,15);
a.sum();
Subtraction s=new Subtraction(20,15);
s.difference();
}
}
25
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
Note: Don’t place Addition.java, Subtraction.java files parallel to the pack directory. If
you place JVM searches for the class files in the current working directory not in the
pack directory.
Access Protection
• Access protection defines actually how much an element (class, method, variable) is
exposed to other classes and packages.
• There are four types of access specifiers available in java:
1. Visible to the class only (private).
2. Visible to the package (default). No modifiers are needed.
3. Visible to the package and all subclasses (protected)
4. Visible to the world (public)
Example:
The following example shows all combinations of the access control modifiers. This
example has two packages and five classes. The source for the first package defines three
classes: Protection, Derived, and SamePackage.
Name of the package: pkg1
This file is Protection.java
package pkg1;
26
PGMCOE, Wagholi.
Unit I V Inheritance, Packages and Interfaces
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
/* class only
* System.out.println("n_priv = "4 + n_priv); */
package pkg1;
class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package - other constructor");
System.out.println("n = " + pro.n);
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
package pkg2;
/* class only
* System.out.println("n_priv = " + n_priv); */
class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
If you want to try these t two packages, here are two test files you can use. The one for
package pkg1 is shown here:
package pkg1;
package pkg2;
29
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
30
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
Java Package
Package in java can be categorized in two form, built-in package and user-defined
package. There are many built-in packages such as java, lang, awt, javax, swing, net, io,
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to
package");
}}
31
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
If you are not using any IDE, you need to follow the syntax
32
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
Exception Handling
The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
What is exception
In java, exception is an event that disrupts the normal flow of the program. It is an object which
is thrown at runtime.
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling.
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception: The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception: The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptionsarenotchecked at compile-timeratherthey arechecked at runtime.
33
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
34
PGMCOE, Wagholi.
Java try block
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Unit IV Inheritance, Packages and Interfaces
Java try block must be followed by either catch or finally block.
1. try{
2. //code that may throw exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw exception
3. }finally{}
Java catch block is used to handle the Exception. It must be used after the try block
only. You can use multiple catch block with a single try.
As displayed in the above example, rest of the code is not executed (in such case, rest of
the code... statement is not printed).
There can be 100 lines of code after exception. So all the code after exception will not be
executed.
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
Output:task1 completed
rest of the code...
class Excep6{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
36
PGMCOE, Wagholi.
int a[]=new int[5];
a[5]=4;
Unit IV Inheritance, Packages and Interfaces
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
1. }
Java finally block
Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not. Java finally
Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Output:5
finally block is always executed
rest of the code...
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
37
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
1. throw exception;
In this example, we have created the validate method that takes integer value as a parameter.
If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
Output:
The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide the
exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any
unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
38
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow..."); } }
Output:
exception handled
normal flow...
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user need.
By the help of custom exception, you can have your own exception and message.
Managing I/O :
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination.
The stream in the java.io package supports many data such as primitives, object, localized
characters, etc.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams −
Java provides strong but flexible support for I/O related to files and networks but this tutorial
covers very basic functionality related to streams and I/O. We will see the most commonly
used examples one by one −
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used
classes are, FileInputStream and FileOutputStream. Following is an example which
makes use of these two classes to copy an input file into an output file −
Example:
40
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}} }}
41
PGMCOE, Wagholi.
Now let's have a file input.txt with the following content −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode. Though there are many
classes related to character streams but the most frequently used classes are, FileReader and
FileWriter. Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at
a time.
We can re-write the above example, which makes the use of these two classes to copy an input file (having unicode
characters) into an output file −
Example
import java.io.*;
42
PGMCOE, Wagholi.
FileReader in = null;
Unit IV Inheritance, Packages and Interfaces
FileWriter out =
null; try {
in = new FileReader("input.txt");
out = new
FileWriter("output.txt"); int c;
out.write(c);}
}finally {
if (in != null) {
in.close();}
if (out != null) {
out.close();
}} }}
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where the user's program
can take input from a keyboard and then produce an output on the computer screen. Java
provides the following three standard streams −
Standard Input − This is used to feed the data to user's program and usually a keyboard
is used as standard input stream and represented asSystem.in.
43
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
Standard Output − This is used to output the data produced by the user's
program and usually a computer screen is used for standard output
stream and represented as System.out.
Standard Error − This is used to output the error data produced by the
user's program and usually a computer screen is used for standard error
stream and represented as System.err.
44
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
45
PGMCOE, Wagholi.
Unit IV Inheritance, Packages and Interfaces
FileInputStream
This stream is used for reading data from the files. Objects can be
created using the keyword new and there are several types of
constructors available.
Following constructor takes a file object to create an input stream object to read
Once you have InputStream object in hand, then there is a list of helper methods
which can be used to read to stream or to do other operations on the stream.
ByteArrayInputStream
DataInputStream
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream object.
47
PGMCOE, Wagholi.