JAVA-UNIT-3(R16)
JAVA-UNIT-3(R16)
UNIT – III
INHERITANCE
METHOD OVERLAODING
SUPER KEYWORD
FINAL KEYWORD
ABSTRACT CLASS
INTERFACES
PACKAGES
CREATING PACKAGES
USING PACKAGES
ACCESS PROTECTION
JAVA.LANG.PACKAGE
EXCEPTIONS
ASSERTIONS
Page 1
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
INHERITANCE IN JAVA
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of 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
parent class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Page 2
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
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 same method and you call it from child class object, there will be
ambiguity to call 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 now.
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. }
Test it Now
Compile Time Error
If a class have multiple methods by same name but different parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
Page 3
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
In java, Method Overloading is not possible by changing the return type of the
method.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
i.e. referred by super reference variable.
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable.
It can be initialized in the constructor only. The blank final variable can be static also which
will be initialized in the static block only.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Page 4
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
11. {
12. Bike obj = new Honda4();
13. obj.run();
14. }
15. }
Test it Now
running safely..
File: TestBank.java
Test it Now
Rate of Interest is: 7 %
INTERFACE IN JAVA
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve fully abstraction and
multiple inheritances in Java.
Page 6
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
There are mainly three reasons to use interface. They are given below.
NOTE: Interface fields are public, static and final by default, and methods
are public and abstract.
As shown in the figure given below, a class extends another class, an interface extends another
interface but a class implements an interface.
In this example, Printable interface have only one method, its implementation
is provided in the A class.
1. interface printable {
2. void print();
3. }
4. class A6 implements printable {
5. public void print()
6. {
Page 7
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
7. System.out.println("Hello");
8. }
9. public static void main(String args[]){
10. A6 obj = new A6();
11. obj.print();
12. }
13. }
Test it Now
Output:Hello
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
8.
9. class A7 implements Printable,Showable{
10.
11. public void print(){System.out.println("Hello");}
12. public void show(){System.out.println("Welcome");}
13.
14. public static void main(String args[]){
15. A7 obj = new A7();
16. obj.print();
Page 8
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
17. obj.show();
18. }
19. }
Test it Now
Output: Hello
Welcome
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
An interface can have another interface i.e. known as nested interface. We will learn it in
detail in the nested classes chapter.
For example:
1. interface printable{
2. void print();
3. interface MessagePrintable
4. {
5. void msg();
6. }
7. }
Page 9
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
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.
Here, we will have the detailed learning of creating and using user-defined packages.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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. }
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file.
Page 10
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
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) 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 A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
6.
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
Page 11
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
Output: Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
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.
Page 12
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
1. //save by B.java
2.
3. package mypack;
4. class B{
5. public static void main(String args[]){
6. pack.A obj = new pack.A();//using fully qualified name
7. obj.msg();
8. }
9. }
Output:Hello
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.
Page 13
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
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;
Suppose there is 10 statements in your program and there occurs an exception at statement 5,
rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception
handling, rest of the exception will be executed. That is why we use exception handling in java.
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.
Page 14
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
3) Error
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1. int a=50/0;//ArithmeticException
If we have null value in any variable, performing any operation by the variable occurs an
NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a
string variable that have characters, converting this variable into digit will occur
NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
Page 15
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
1. try
2. catch
3. finally
4. throw
5. throws
Java try block is used to enclose the code that might throw an exception. It must be used
within the method.
Java catch block is used to handle the Exception. It must be used after the try block only.
Page 16
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
EXAMPLE:
Output:
Now, as displayed in the above example, rest of the code is executed i.e. rest of the code...
statement is printed.
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.
EXAMPLE:
Page 17
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
11. }
Test it Now
Output:Exception in thread main java.lang.ArithmeticException:/ by zero
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.
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:
Page 18
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
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.
Let's see the example of java throws clause which describes that checked exceptions can be
propagated by throws keyword.
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. }
Test it Now
Output:
exception handled
normal flow...
Page 19
YEAR: II BTECH BRANCH: CSE SUBJECT: JAVA
In exception enrichment you do not wrap exceptions. Instead you add contextual information
to the original exception and rethrow it. Rethrowing an exception does not reset the stack trace
embedded in the exception.
Here is an example:
try{
method1();
} catch(EnrichableException e){
throw e;
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:
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. }
Page 21