22CS202 Java Unit-2
22CS202 Java Unit-2
JAVA PROGRAMMING
UNIT II
UNIT 2 - INHERITANCE
• Inheritance can be defined as the process of acquiring
all the properties and behaviors of one class to
another
• Inheritance represents the IS-A relationship, also Figure 2.1 Instance for Inheritance
Syntax:
class subClass extends superClass
{
//methods and fields
}
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
Super Class/Parent Class: Superclass is the class from where a subclass inherits the
• Single Inheritance
• Hierarchical Inheritance
• Multilevel Inheritance
• Hybrid Inheritance
Types of Inheritance
Types of Inheritance and Syntax
class Mango extends Fruit
Single Inheritance {
Process of extending single subclass from single String name = “Mango";
void printName()
super class.
{
System.out.println("Name is: " + name);
}
}
class SingleDemo
{
Example:
public static void main(String args[])
class Fruit
{
{
Mango m1 = new Mango();
String taste = “Sweet";
m1.printTaste();
void printTaste() m1.printName();
{ }
OUTPUT
System.out.println(“Taste is: " + taste); }
Taste is: Sweet
}
Name is: Mango
}
class Mango extends Fruit
Hierarchical Inheritance
{
Process of extending more than one subclasses from String name = “Mango";
class HierarchicalDemo
{
public static void main(String args[])
{ OUTPUT
Taste is: Sweet
Mango m1 = new Mango();
Name is: Mango
m1.printTaste();
Taste is: Sweet
m1.printName(); Name is: Apple
Apple a1 = new Apple();
a1.printTaste();
a1.printName();
}
}
class Mango extends Fruit
Multilevel Inheritance
{
Process of extending subclass from another sub String name = “Mango";
class MultilevelDemo
{
public static void main(String args[])
{ OUTPUT
Taste is: Sweet
Malgova m1 = new Malgova();
Name is: Mango
m1.printTaste();
Weight is: 2
m1.printName();
m1.printWeight();
}
}
class mango extends fruit
Hybrid Inheritance
{
Process of extending new classes by combining String name = “Mango";
}
}
class HybridDemo
Hybrid Inheritance {
public static void main(String args[])
class PapayawithoutSeed extends papaya {
{ mango m1 = new mango();
int weight = 5; m1.printTaste();
void printWeight() m1.printName();
{ PapayawithoutSeed a1 = new
System.out.println(“Weight is: " + PapayawithoutSeed();
weight); a1.printTaste();
} a1.printName();
} a1.printWeight(); OUTPUT
Taste is: Sweet
}
Name is: Mango
}
Taste is: Sweet
Name is: Papaya
Weight is: 5
Member Access and Inheritance class B extends A
(Private) {
int total;
void sum()
Although a subclass includes all of the members of its
{
superclass, it cannot access those members of the System.out.println("Accessing Protected
superclass that have been declared as private. member of Super class");
total=i+j; // Error, J is not accessible here
EXAMPLE
}
class A }
{ class PrivateAccessDemo
int i; //default access {
public static void main(String args[])
private int j; //private to A
{
void setij(int x,int y) B subob = new B();
{ subob.setij(10,20);
subob.sum();
i=x; j=y;
System.out.println("Total :
} "+subob.total);
OUTPUT
} }
Error
}
Member Access and Inheritance
(Protected)
Overriden Method
Overriding Method
METHOD OVERRIDING
• If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
• In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
• Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.
• The method must have the same name as in the parent class.
• The method must have the same parameter as in the parent class.
super.variable_name
Uses of Super refers to the variable in
the parent class.
• When we have the same variable name in both super class and subclass,
super.variablename is used to access the super class variable.
Example 1: Example 2:
class A
class A {
{
int val=10;
int val=10;
}
}
class B extends A
class B extends A
{
{
int val=20;
int val=20;
void disp() void disp()
{ {
System.out.println("Value is : "+val); System.out.println("Value is : "+super.val);
} }
} }
class Test class Test
{
{
public static void main(String args[])
public static void main(String args[])
{
{
B b = new B();
B b = new B();
b.disp();
b.disp();
}
} }
}
Output : Output :
3) super() invokes the constructor of the parent class
• Subclass constructor can use super() for invoking the super class constructor explicitly
Syntax
subclassname()
{
super();
// sub-class constructor statements
}
Conditions to use super() in constructor
• super() should be the first statement in subclass constructor
• Must be used only in the subclass constructor
• The parameters in the super call must match the order and type of variables declared
in the super class constructor.
Example :
class A
{
A()
{
System.out.println("Base Class default Constructor");
}
}
class B extends A
{
B()
{
super();
System.out.println("Derived Class default Constructor");
}
class Test
{
public static void main(String args[]) Output:
{
B b = new B(); // invoking sub-class constructor Base Class default Constructor
}
Derived Class default Constructor
}
ABSTRACT METHODS
AND
ABSTRACT CLASSES
ABSTRACT CLASSES
Data abstraction is the process of hiding the implementation details and
• A method which is declared as abstract and does not have implementation is known as
an abstract method.
…
}
Rules for Abstract Class
1. An abstract class must be declared with an abstract keyword.
5. It can have final methods which will force the subclass not to change the body
of the method.
• Thus, polymorphism is the ability of an object to make more than one form.
Run Time Polymorphism
• Run-time polymorphism refers to behavior(method) that is resolved when your Java class is run by the
JVM.
• Method overriding allows child classes to provide their own implementation of a method also defined in the
parent class.
• An overridden method is called through the reference variable of a superclass. This process is
called as up casting.
• The JVM decides which version of the method to call based on the object through which the method is
invoked.
Up casting
Example for Run Time Polymorphism: class Circle extends Shape //subclass 3
{
abstract class Shape int circlearea;
{ void Area() //Overrides the abstract method Area() of the super
int a=3,b=4; class
abstract void Area(); {
} circlearea=(int) (3.14*a*a);
System.out.println(“Area of circle is:“+circlearea);
class Rectangle extends shape //subclass 1
}
{
int rectarea; }
void Area() //Overrides the abstract method Area() of the super class class Demo
{ {
OUTPUT:
rectarea=a*b; public static void main(String[] args)
Area of rectangle is: 12
System.out.println(“Area of rectangle is:“ +rectarea); {
} Area of triangle is: 6
s.Area();
class Triangle extends Shape //subclass 2
{ Shape s=new Triangle();
int triarea;
void Area() //Overrides the abstract method Area() of the super class s.Area();
{ Shape s=new Circle();
triarea=(int) (0.5*a*b);
System.out.println(“Area of triangle is:“ +triarea); s.Area();
} }
FINAL KEYWORD IN JAVA
FINAL KEYWORD IN JAVA
Example: Output :
public class Travel
Exception in thread "main" java.lang.Error:
{
Unresolved compilation problem:
final int SPEED=60;
void increaseSpeed()
The final field Travel.SPEED cannot be assigned.
{
SPEED=70;
} The above code will give you Compile time
public static void main(String args[])
error, as we are trying to change the value of a
{
final variable ‘SPEED’.
Travel t=new Travel();
t.increaseSpeed();
}
final method
When a method is declared as final, it is called as final method.
A final method cannot be overridden.
class Demo
Example:
{
class Parent public static void main(String args[])
{
{
Child c = new Child();
final void disp() c.disp();
}
{
}
System.out.println("disp() method of parent class");
Output : We will get the below error as we are overriding
}
the disp() method of the Parent class.
}
class Child extends Parent
Exception in thread "main" java.lang.VerifyError: class
{
com.javainterviewpoint.Child overrides final method disp.()
void disp()
at java.lang.ClassLoader.defineClass1(Native Method)
{
at java.lang.ClassLoader.defineClass(Unknown Source)
System.out.println("disp() method of child class");
at java.security.SecureClassLoader.defineClass(Unknown
}
Source)
}
final class
When a class is declared as final, it cannot be extended.
Final classes prevent Inheritance. If you try, it gives a compile time error.
interface Bank {
float rateOfInterest();
}
}
}
Example 2:
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
Hello
}
}
Example 3:
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Output:
drawing circle
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces it is known as multiple inheritance.
Example 1:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
Example
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}
Key points to remember about interfaces:
interface A
int x=10;
}
interface B
int x=100;
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
Advantages of interface in java:
▪Without bothering about the implementation part, we can achieve the security of Implementation.
▪ In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement
more than one interface.
Difference between Abstract Class and Interface
Static Methods in a Interface
• static methods contain the complete definition of the function.
• Since the definition is complete and the method is static, these methods cannot be overridden or changed
in the implementation class.
• Keyword used is static.
Example:
interface NewInterface
{
static void hello() // static method
{
System.out.println("Hello, New Static Method Here");
}
@Override
public void overrideMethod(String str)
{
System.out.println(str);
}
}
Output:
Hello, New Static Method Here Hello, Override Method here
• A simple static method is defined and declared in an interface which
is being called in the main() method of the Implementation Class
InterfaceDemo.
• Unlike the default method, the static method hello() defined in the
interface NewInterface, cannot be overridden in implementing the
class.
LAB Exercise - Design a Java interface for Stack ADT and develop two
different classes that implements this interface, one using array and the
other using linked list.
import java.io.*;
interface Mystack
{
public void pop();
public void push();
public void display();
}
class Stack_array implements Mystack
{
final static int n=5;
int stack[]=new int[n];
int top=-1;
public void push()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(top==(n-1))
{
System.out.println(" Stack Overflow");
return;
}
else
{
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
stack[++top]=ele;
}
}
catch(IOException e)
{
System.out.println("e");
}
}
public void pop()
{
if(top<0)
{
System.out.println("Stack underflow");
return;
}
else
{
int popper=stack[top];
top--;
System.out.println("Popped element:" +popper);
}
}
public void display()
{
if(top<0)
{
System.out.println("Stack is empty");
return;
}
else
{
String str=" ";
for(int i=0; i<=top; i++)
str=str+" "+stack[i]+" <--";
System.out.println("Elements are:"+str);
}
}
}
class Link
{
public int data;
public Link nextLink;
public Link(int d)
{
data= d;
nextLink=null;
}
public void printLink()
{
System.out.print(" --> "+data);
}
}
class Stack_List implements Mystack
{
private Link first;
public Stack_List()
{
first = null;
}
public boolean isEmpty()
{
return first == null;
}
public void push()
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the element");
int ele=Integer.parseInt(br.readLine());
Link link = new Link(ele);
link.nextLink = first;
first = link;
}
catch(IOException e)
{
System.err.println(e);
}
}
public Link delete()
{
Link temp = first;
try
{
first = first.nextLink;
}
catch(NullPointerException e)
{
throw e;
}
return temp;
}
public void pop()
{
try
{
Link deletedLink = delete();
System.out.println("Popped: "+deletedLink.data);
}
catch(NullPointerException e)
{
throw e;
}
public void display()
{
if(first==null)
System.out.println("Stack is empty");
else
{
Link currentLink = first;
System.out.print("Elements are: ");
while(currentLink != null)
{
currentLink.printLink();
currentLink = currentLink.nextLink;
}
System.out.println("");
}
}
}
class StackADT
{
public static void main(String arg[])throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Implementation of Stack using Array");
Stack_array stk=new Stack_array();
int ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk.push();
break;
case 2:
stk.pop();
break;
case 3:
stk.display();
break;
case 4:
System.exit(0);
}
}
while(ch<5);
System.out.println("Implementation of Stack using Linked List");
Stack_List stk1=new Stack_List();
ch=0;
do
{
System.out.println("1.Push 2.Pop 3.Display 4.Exit");
System.out.println("Enter your choice:");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
stk1.push();
break;
case 2:
try
{
stk1.pop();
}
catch(NullPointerException e)
{
System.out.println("Stack underflown");
}
break;
case 3:
stk1.display();
break;
default:
System.exit(0);
}
}
while(ch<5);
}
}
OUTPUT
Implementation of Stack using Array
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
15
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
1
Enter the element
25
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
3
Elements are: 10 <-- 15 <-- 25 <--
1.Push 2.Pop 3.Display 4.Exit 5.Use Linked List
Enter your choice:
5
Implementation of Stack using Linked List
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
15
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
1
Enter the element
20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: --> 20 --> 15 --> 10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
2
Popped: 20
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
3
Elements are: --> 15 --> 10
1.Push 2.Pop 3.Display 4.Exit
Enter your choice:
4
Topics
Introduction Example: Multiple Catch Statement
Types of Errors Nested try Statements
Exceptions Java Exception Hierarchy
Exception Handling Fundamentals Finally Block
Common JAVA Exceptions Example with finally block
Uncaught Exceptions Using throw Keyword
Syntax of Exception Handling Code Example
Example: Divide by Zero without Exception Java’s Built-in Exceptions
Handling
Example: Handling Arithmetic Exception
Types of Errors
Errors
may broadly be classified into two categories. They are
Compile – Time errors
All syntax errors will be detected and displayed by the JAVA compiler and
therefore these errors are known as compile – time errors. Most of the compile –
time errors are due to typing mistakes. The most common error are.
Missing semicolons
Missing brackets in classes and methods
Misspellings of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables
Incompatible types in assignments / initializations
use of = in place of == operator
And so on.
Types of Errors
Errors may broadly be classified into two categories. They are
if the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.
Exception
catch block handler
Statement that handles
the exception
Types of Errors
Errors may broadly be classified into two categories. They are
Compile – Time errors
All syntax errors will be detected and displayed by the JAVA compiler and
therefore these errors are known as compile – time errors. Most of the
compile – time errors are due to typing mistakes. The most common error
are.
Missing semicolons
Missing brackets in classes and methods
Misspellings of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables
Incompatible types in assignments / initializations
use of = in place of == operator
And so on.
Types of Errors
Errors may broadly be classified into two categories. They are
Run – Time errors
After compilation process is completed, the program has to be tested for
various inputs. If the program produce wrong results due to wrong logic or
may terminate due to errors. Such errors are called Run – Time errors.
Most common run – time errors are.
Diving an integer by 0.
Accessing an element that is out of bounds of an array.
Attempting to use a negative size for an array.
Trying to store a value of an incompatible types.
Converting invalid String to a number
Accessing a character that is out of bounds of a String.
And many more.
When such errors are encountered, java typically generates an error
message and aborts the program
Exceptions
An Exception is a condition that is caused by a run – time error in the
program.
if the exception object is not caught and handled properly, the interpreter
will display an error message and will terminate the program.
The exception handling code basically consists of two segments. One to detect error
and to throw exceptions and the other to catch exception and to take appropriate
actions.
Common Java Exceptions
The programmer always be on the lookout for places in the program where exception could
be generated. Some common exceptions that we must watch out for catching are listed.
Exception Type Cause of Exception
ArithmeticException Caused by math errors such as division by zero
ArrayIndexOutOfBoundExc
Caused by bad array indexes
eption
Caused when a program tries to store the wrong type
ArrayStoreException
of data in an array
FileNotFoundException Caused by an attempt to access a nonexistent file
NullPointerException Caused by referencing a null object
Caused when a conversion between strings and
NumberFormatException
numbers fails
StackOverFlowException Caused when the system runs out of stack space.
Syntax of Exception Handling
The basic concepts of exception handling are throwing an exception and
catching it. This is illustrated in figure as shown.
Exception
try block object creato
r
Statement that causes
an exception
Throws exce
ption
object
Exception
catch block handler
Statement that handles
the exception
Syntax of Exception Handling
Java uses the keyword try to preface a block of code that is likely to cause an error
condition throw an exception.
A catch block defined by the keyword catch, catches the exception thrown by the try
block and handles it appropriately.
Figure shows a small portion of the inheritance hierarchy for class Throwable
(a subclass of Object), which is the superclass of class Exception.
The finally block always executes when the try block exits. This ensures that the
finally block is executed even if an unexpected exception occurs. But finally is useful
for more than just exception handling.
it allows the programmer to avoid having cleanup code accidentally bypassed by a
return, continue, or break. Putting cleanup code in a finally block is always a good
practice, even when no exceptions are anticipated.
The finally block is used for resource de-allocation.
Placed after the last catch block.
Example: With Finally Block
Output:
Throwing Our own Exceptions
Example:
throw new ArithmeticException();
throw new NumberFormatException();
Example using Throw
THANK YOU