Java Basic Unit 3
Java Basic Unit 3
Inheritance in Java
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object.
• The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes.
• When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your
current class also.
• Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee.
It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{ 0
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as
of Employee class i.e. code reusability.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
2. void eat()
3. {System.out.println("eating...");}
4. }
5. class Dog extends Animal{
6. void bark()
7. {System.out.println("barking...");}
8. }
9. class TestInheritance{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. d.bark();
13. d.eat();
14. }}
Output:
barking...
eating...
Multilevel Inheritance Example
When there is a chain of inheritance, it is known as multilevel inheritance.
As you can see in the example given below, BabyDog class inherits the Dog class
which again inherits the Animal class, so there is a multilevel inheritance.
1. class Animal{
2. void eat()
3. {System.out.println("eating...");}
4. }
5. class Dog extends Animal{
6. void bark()
7. {System.out.println("barking...");}
8. }
9. class BabyDog extends Dog{
10. void weep()
11. {System.out.println("weeping...");}
12. }
13. class TestInheritance2{
14. public static void main(String args[]){
15. BabyDog d=new BabyDog();
16. d.weep();
17. d.bark();
18. d.eat();
19. }}
Output:
weeping...
barking...
eating...
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class
object, there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Compile Time Error
Abstract class in Java
Points to Remember
Mostly, we don't know about the implementation class (which is hidden to the end
user), and an object of the implementation class is provided by the factory method.
In this example, if you create the instance of Rectangle class, draw() method of
Rectangle class will be invoked.
File: TestAbstraction1.java
1. class Bike12{
2. abstract void run();
3. }
compile time error
Rule: If you are extending an abstract class that has an abstract method, you must
either provide the implementation of the method or make this class abstract.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Output:
Syntax:
1. interface <interface_name>{
2. // declare constant fields
3. // declare methods that abstract
4. // by default.
5. }
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
The implementation part is hidden by the user who uses the interface.
Output:
drawing circle
Output:Hello
Welcome
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }
Output:
Hello
Welcome
1) Abstract class can have abstract and Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Output:
I am a
I am b
I am c
I am d
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
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, util, sql
etc.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
For example
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can
use any directory name like /home (in case of Linux), d:/abc (in case of windows) etc.
If you want to keep the package within the same directory, you can use . (dot).
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
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.
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
//save by B.java
1. package mypack;
2. import pack.A;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
Output:Hello
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.
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
//save by B.java
1. package mypack;
2. class B{
3. public static void main(String args[]){
4. pack.A obj = new pack.A();//using fully qualified name
5. obj.msg();
6. }
7. }
Output:Hello
Note: Sequence of the program must be package then import then class.
Subpackage in java
• Package inside the package is called the subpackage.
• It should be created to categorize the package further.
Let's take an example, Sun Microsystem has definded a package named java that
contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes are for
Input/Output operation,
Socket and ServerSocket classes are for networking etc and so on.
So, Sun has subcategorized the java package into subpackages such as lang, net, io
etc. and put the Input/Output related classes in io package, Server and ServerSocket
classes in net packages and so on.
Example of Subpackage
1. package com.vignan.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
Output:Hello subpackage
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that directly inherit the Throwable class except
RuntimeException and Error are known as checked exceptions.
2) Unchecked Exception
3) Error
Error is irrecoverable.
Java provides five keywords that are used to handle the exception. The
following table describes each.
Keyword Description
try The "try" keyword is used to specify a block where we
should place an exception code. It means we can't use try
block alone. The try block must be followed by either catch
or finally.
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
1. String s=null;
2. System.out.println(s.length());//NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
• Java try block is used to enclose the code that might throw an
exception.
• It must be used within the method.
• If an exception occurs at the particular statement in the try block,
the rest of the block code will not execute.
• So, it is recommended not to keep the code in try block that will not
throw an exception.
• Java try block must be followed by either catch or finally block.
1. try{
2. //code that may throw an exception
3. }catch(Exception_class_Name ref){}
1. try{
2. //code that may throw an exception
3. }finally{}
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter. The declared exception must be the
parent class exception( i.e., Exception) or the generated exception type.
However, the good approach is to declare the generated type of
exception.
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
But if the application programmer handles the exception, the normal flow
of the application is maintained, i.e., rest of the code is executed.
Problem without exception handling
Example 1
TryCatchExample1.java
Output:
As displayed in the above example, the rest of the code is not executed
(in such case, the rest of the code statement is not printed).
There might be 100 lines of code after the exception. If the exception is
not handled, all the code below the exception won't be executed.
Example 2
TryCatchExample2.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
In this example, we also kept the code in a try block that will not throw
an exception.
TryCatchExample3.java
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of
the block code will not execute.
Example 4
TryCatchExample4.java
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5
TryCatchExample5.java
Output:
Example 6
TryCatchExample6.java
1. public class TryCatchExample6 {
2.
3. public static void main(String[] args) {
4. int i=50;
5. int j=0;
6. int data;
7. try
8. {
9. data=i/j; //may throw exception
10. }
11. // handling the exception
12. catch(Exception e)
13. {
14. // resolving the exception in catch block
15. System.out.println(i/(j+2));
16. }
17. }
18. }
Output:
25
Example 7
In this example, along with try block, we also enclose exception code in
a catch block.
TryCatchExample7.java
Output:
Here, we can see that the catch block didn't contain the exception code.
So, enclose exception code within a try block and use catch block only
to handle the exceptions.
Example 8
In this example, we handle the generated exception (Arithmetic
Exception) with a different type of exception class
(ArrayIndexOutOfBoundsException).
TryCatchExample8.java
Output:
A try block can be followed by one or more catch blocks. Each catch
block must contain a different exception handler. So, if you have to
perform different tasks at the occurrence of different exceptions, use
java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch
block is executed.
o All catch blocks must be ordered from most specific to most
general, i.e. catch for ArithmeticException must come before catch
for Exception.
Example 1
Let's see a simple example of java multi-catch block.
MultipleCatchBlock1.java
Keep Watching
Example 2
MultipleCatchBlock2.java
Output:
Sometimes a situation may arise where a part of a block may cause one
error and the entire block itself may cause another error. In such cases,
exception handlers have to be nested.
Syntax:
1. ....
2. //main try block
3. try
4. {
5. statement 1;
6. statement 2;
7. //try catch block within another try block
8. try
9. {
10. statement 3;
11. statement 4;
12. //try catch block within nested try block
13. try
14. {
15. statement 5;
16. statement 6;
17. }
18. catch(Exception e2)
19. {
20. //exception message
21. }
22.
23. }
24. catch(Exception e1)
25. {
26. //exception message
27. }
28. }
29. //catch block of parent (outer) try block
30. catch(Exception e3)
31. {
32. //exception message
33. }
34. ....
Java Nested try Example
Example 1
Let's see an example where we place a try block within another try block
for two different exceptions.
NestedTryBlock.java
Output:
When any try block does not have a catch block for a particular
exception, then the catch block of the outer (parent) try block are
checked for that exception, and if it matches, the catch block of outer try
block is executed.
If none of the catch block specified in the code is unable to handle the
exception, then the Java runtime system will handle the exception. Then
it displays the system generated message for that exception.
o finally block in Java can be used to put "cleanup" code such as closing
a file, closing connection, etc.
o The important statements to be printed can be placed in the finally
block.
Let's see the different cases where Java finally block can be used.
Case 1: When an exception does not occur
Let's see the below example where the Java program does not throw
any exception, and the finally block is executed after the try block.
TestFinallyBlock.java
1. class TestFinallyBlock {
2. public static void main(String args[]){
3. try{
4. //below code do not throw any exception
5. int data=25/5;
6. System.out.println(data);
7. }
8. //catch won't be executed
9. catch(NullPointerException e){
10. System.out.println(e);
11. }
12. //executed regardless of exception occurred or not
13. finally {
14. System.out.println("finally block is always executed");
15. }
16.
17. System.out.println("rest of phe code...");
18. }
19. }
Output:
Example:
Let's see the following example where the Java code throws an
exception and the catch block handles the exception. Later the finally
block is executed after the try-catch block. Further, the rest of the code
is also executed normally.
TestFinallyBlock2.java
Output:
Rule: For each try block there can be zero or more catch blocks, but
only one finally block.
Note: The finally block will not be executed if the program exits (either
by calling System.exit() or by causing a fatal error that causes the
process to abort).
TestThrow1.java
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 above code throw an unchecked exception. Similarly, we can also throw
unchecked and user defined exceptions.
Note: If we throw unchecked exception from a method, it is must to handle the exception
or declare in throws clause.
TestThrow3.java
Output:
Testthrows1.java
1. import java.io.IOException;
2. class Testthrows1{
3. void m()throws IOException{
4. throw new IOException("device error");//checked exception
5. }
6. void n()throws IOException{
7. m();
8. }
9. void p(){
10. try{
11. n();
12. }catch(Exception e){System.out.println("exception handled");}
13. }
14. public static void main(String args[]){
15. Testthrows1 obj=new Testthrows1();
16. obj.p();
17. System.out.println("normal flow...");
18. }
19. }
Output:
exception handled
normal flow...
Rule: If we are calling a method that declares an exception, we must either caught or
declare the exception.
1. Case 1: We have caught the exception i.e. we have handled the exception using
try/catch block.
2. Case 2: We have declared the exception i.e. specified throws keyword with the
method.
Testthrows2.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. public class Testthrows2{
8. public static void main(String args[]){
9. try{
10. M m=new M();
11. m.method();
12. }catch(Exception e){System.out.println("exception handled");}
13.
14. System.out.println("normal flow...");
15. }
16. }
Output:
exception handled
normal flow...
o In case we declare the exception, if exception does not occur, the code will be
executed fine.
o In case we declare the exception and the exception occurs, it will be thrown at
runtime because throws does not handle the exception.
Testthrows3.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. System.out.println("device operation performed");
5. }
6. }
7. class Testthrows3{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
B) If exception occurs
Testthrows4.java
1. import java.io.*;
2. class M{
3. void method()throws IOException{
4. throw new IOException("device error");
5. }
6. }
7. class Testthrows4{
8. public static void main(String args[])throws IOException{//declare exception
9. M m=new M();
10. m.method();
11.
12. System.out.println("normal flow...");
13. }
14. }
Output:
Assertion:
• Assertion is a statement in java.
• It can be used to test your assumptions about the program.
• While executing assertion, it is believed to be true.
• If it fails, JVM will throw an error named AssertionError. It is mainly used for
testing purpose.
Advantage of Assertion:
It provides an effective way to detect and correct programming errors.
1. assert expression;
1. import java.util.Scanner;
2.
3. class AssertionExample{
4. public static void main( String args[] ){
5.
6. Scanner scanner = new Scanner( System.in );
7. System.out.print("Enter ur age ");
8.
9. int value = scanner.nextInt();
10. assert value>=18:" Not valid";
11.
12. System.out.println("value is "+value);
13. }
14. }
15.
16.
If you use assertion, It will not run simply because assertion is disabled by default. To enable the
assertion, -ea or -enableassertions switch of java must be used.