Java Programming: Inheritance, Packages, Exceptions Topics Covered in This Unit
Java Programming: Inheritance, Packages, Exceptions Topics Covered in This Unit
Java Programming: Inheritance, Packages, Exceptions Topics Covered in This Unit
UNIT-3
Inheritance, packages, exceptions
Hierarchical Abstractions:
• Humans manage complexity through abstraction.
• For example, people do not think of a car as a set of tens of thousands of individual parts.
• They think of it as a well defined object with its own unique behavior.
• This abstraction allows people to use a car without being overwhelmed by the complexity of the
parts that form the car.
• They can ignore the details of how the engine, transmission, and braking systems work.
• These hierarchical abstractions are achieved by aggregation or inheritance.
Aggregation:
• Aggregation in Java is a relationship between two classes that is best described as a "has-a" and
"whole/part" relationship.
• It is a more specialized version of the association relationship.
• The aggregate class contains a reference to another class and is said to have ownership of that
class. Each class referenced is considered to be part-of the aggregate class.
• Ownership occurs because there can be no cyclic references in an aggregation relationship.
Inheritance:
• Inheritance is an important pillar of OOP(Object Oriented Programming).
• It is the mechanism in java by which one class is allow to inherit the features(fields and
methods) of another class.
Hierarchy caused by Aggregation Vs inheritance:
Aggregation Vs Inheritance:
• Both associations describe trees (hierarchies)
• Aggregation tree describes “a-part-of “relationships.
• Inheritance tree describes "kind-of" relationships.
• Aggregation is part-of or part-whole relationship (by reference)
Ex : Car has Engine and Transmission
• Inheritance is kind of or is-a or parent-child relationship
Ex: Car and Bus are kind of Vehicles
• Aggregation relates instances (involves two or more different objects)
• Inheritance relates classes (a way to structure the description of a single object)
Inheritance:
• Inheritance is the mechanism of deriving new class from old one.
• Old class is known as Base class or super class or parent class.
• The inherited new class is known as derived class or sub class or child class.
• The sub class inherits all of its instance variables and methods defined by super class.
• The sub class also adds its own specialized features.
• A child class of one parent can be the parent of another child, forming class hierarchies.
• The class hierarchy determines how methods are executed.
• inheritance is transitive.
• The benefits of inheritance is code reusability, better ability to extend ( adding new features ) or
enhance ( improving the existing features ).
Benefits of inheritance:
• The most frequent use of inheritance is for deriving classes using existing classes, which provides
reusability. The existing classes remain unchanged. By reusability, the development time of
software is reduced.
• The derived classes extend the properties of base classes to generate more dominant objects.
• The same base classes can be used by a number of derived classes in class hierarchy.
• When a class is derived from more than one class, all the derived classes have similar properties
to those of base classes
Important terminology in inheritance:
Super Class: The class whose features are inherited is known as super class(or a base class or a
parent class).
Sub Class: The class that inherits the other class is known as sub class(or a derived class, extended
class, or child class). The subclass can add its own fields and methods in addition to the superclass
fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new
class and there is already a class that includes some of the code that we want, we can derive our
new class from the existing class. By doing this, we are reusing the fields and methods of the
existing class.
Defining a sub class to super class:
• Syntax to define a sub class
class <sub_class_name> extends <super_class_name>
{
// members in the sub class
}
• 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 parent or super class or base class
• The new class is called child class or subclass or derived class.
Types of inheritance:
Simple(Single) inheritance:
• Classes are inherited from other class by declaring them as a part of its definition
• For e.g.
– class MySubClass extends MySuperClass
• extends keyword declares that MySubClass inherits the parent class MySuperClass.
• Simple inheritance is a parent-child relationship between two classes.
• It allows sharing of the behavior of the parent class into its child classes
• The child class can add new behavior or override existing behavior from parent.
• Java forces a class to have exactly one parent
Program to demonstrate Simple(single) inheritance:
Output:
Multi-Level Inheritance:
• It is a ladder or hierarchy of single level inheritance.
• Multiple classes are involved in inheritance, but one class extends only one.
• The lowermost subclass can make use of all its super classes' members.
class Rectangle {
int length;
int width;
Rectangle() { }
public Rectangle(int l, int w) {
length = l;
width = w;
}
}
class Box extends Rectangle {
int height;
Box() { }
public Box (int l, int w, int h) {
length = l;
width = w;
height = h;
}
public int volume() {
return (length * width * height);
}
}
class SolidBox extends Box {
int density;
public SolidBox(int l, int w, int h, int d) {
length = l;
width = w;
height = h;
density = d;
}
public int weight() {
return(super.volume() * density);
}
}
class MultiLevelInheritTest
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(5,8);
System.out.println("Area of rectangle : " + (r1.length * r1.width));
Box b1 = new Box(7,5,9);
System.out.println("Volume of the box : " + b1.volume());
SolidBox m1 = new SolidBox(10,15,25,3);
System.out.println( "Volume of the Solid box : " + m1.volume());
System.out.println("The weight of the Solid Box : " + m1.weight() + " KiloGrams.");
}
}
Output:
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 subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
• The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.
Output:
Method overloading Vs overriding:
Hierarchical Inheritance:
• In this type of inheritance there are multiple classes which are derived from one base class.
• It is used when one class feature is required in multiple classes.
class Animal {
void show() {
System.out.println("I am animal");
}
}
class Cow extends Animal {
// overriding method
void show() {
System.out.println("I am Cow");
}
}
class Cat extends Animal {
// overriding method
void show() {
System.out.println("I am Cat");
}
}
class Dog extends Animal {
// overriding method
void show() {
System.out.println("I am Dog");
}
}
class DynamicMethodDispatch {
public static void main(String[] args) {
Animal a1;
a1 = new Animal();
a1.show();
// up casting
a1 = new Cow();
a1.show();
a1 = new Cat();
a1.show();
a1 = new Dog();
a1.show();
}
}
Output:
Super keyword:
• Super keyword is used to access super class members.
• We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have data fields with same name.
• The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
• The super keyword can also be used to invoke the parent class parameterized constructor from
sub class constructor.
• When super class constructor is invoked in subclass constructor, the call for super class
constructor should be first statement in sub class constructor.
class Parent {
int x;
Parent(int i ) {
x = i;
}
void show() {
System.out.println(" Parent : x = " + x);
}
}
class Child extends Parent {
int x;
int y;
Child(int i, int j, int k) {
super(i);
x = j;
y = k;
}
void show() {
System.out.println("Parent : x = " + super.x);
System.out.println("Child : x = " + x);
System.out.println("Child : y = " + y);
}
void parent_show() {
super.show();
}
}
class SuperDemo {
public static void main(String[] args) {
Child c1 = new Child(2,3,4);
c1.show();
c1.parent_show();
}
}
Output:
Final keyword:
• final keyword is used in different contexts. First of all, final is a non-access modifier
applicable only to a variable, a method or a class.
• Declaring constants (used with variable and argument declaration)
– final int MAX=100;
• Preventing method overriding by subclass (used with method declaration)
– final void show (final int x)
• Preventing to create subclass (used with class declaration).
– final class Demo {}
Final variables
– When a variable is declared with final keyword, it’s value can’t be modified, essentially, a constant.
– If the final variable is a reference, this means that the variable cannot be re-bound to reference
another object, but internal state of the object pointed by that reference variable can be changed
– For example, you can add or remove elements from final array or final collection.
– It is good practice to represent final variables in all uppercase, using underscore to separate words.
Example:
int x = 30; final int y = 30;
x = 45; // O.K. x = 45; // error, because y is final constant.
Final methods:
• A final method cannot be overridden.
• It means that a sub class can call the final method of parent class, but it cannot override it.
• Final methods exhibit early binding.
• The use of final method is to protect against accidental overriding, or maybe performance.
Example :
class A {
int x = 10;
final void show() {
System.out.println(“x = “ + x);
}
}
class B extends A {
void show() { // raises compilation error- final method cannot be overriden
// code
}
}
Final Classes:
• We can also declare an entire class final.
• We cannot write subclass to final class.
• This is particularly useful, for example, when creating an immutable class like the String class.
Abstract Class:
• Abstraction is the quality of dealing with ideas rather than events.
• In Object-oriented programming, abstraction is a process of hiding the implementation details
from the user, only the functionality will be provided to the user.
• In other words, the user will have the information on what the object does instead of how it
does it.
• In Java, abstraction is achieved using Abstract classes and interfaces.
• In general, every method has implementation in the class definition.
Ex: void show()
{
System.out.println("This is concrete method");
}
• But an abstract method does not have method body, only declaration.(like pure virtual functions
in C++).
• Ex: abstract void show();
• An abstract method contains a method signature, but no method body. Instead of curly braces,
an abstract method will have a semi colon (;) at the end.
• When a class contains at least one abstract method, the class is known as abstract class.
• Ex: abstract class Demo
{
int x, y;
Demo( int a, int b) {
x = a;
y = b;
}
void show() {
System.out.println("x = " + x + ", y = " + y);
}
abstract void add();
}
Program to demonstrate an abstract class:
abstract class Shape
{
int dim1;
int dim2;
Shape(int a, int b) {
dim1 = a;
dim2 = b;
}
abstract double area();
}
class ImpRectangle extends Shape
{
ImpRectangle(int a, int b) {
super(a,b);
}
public double area() {
return (dim1*dim2);
}
}
class ImpTriangle extends Shape
{
ImpTriangle(int a, int b) {
super(a,b);
}
public double area() {
return (dim1*dim2)/2;
}
}
class AbstractTest
{
public static void main(String[] args) {
Shape r = new ImpRectangle(20,25);
Shape t = new ImpTriangle(20,25);
System.out.println("Area of Rectangle : " + r.area());
System.out.println("Area of Triangle : " + t.area());
}
}
Output:
Output:
Purpose of Interfaces:
• Interfaces are used to separate abstraction from implementation.
• It is used to identify a common set of methods for the group of classes that implement the
interface.
• It is also used to share constants between classes.
• Interfaces are used to provide the benefits of multiple-inheritance without its implementation
difficulties.
• Interfaces without methods are known as marker interfaces, which are used to provide eligibility
to perform some actions like serialization etc.,
• Interfaces are used to create a collection of non-related sub class objects like an array.
• Interfaces provide a control on its sub classes to maintain the method signatures are same
across all its sub classes. (Dynamic polymorphism with non-related classes)
• Reference variables of interfaces can provide security across internet, in client server
programming.
Extending Interfaces:
• An interface can extend another interface. The ‘extends’ keyword is used to extend an interface,
and the child interface inherits the methods of the parent interface.
• An interface can extend more than one parent interface. The ‘extends’ keyword is used once,
and the parent interfaces are declared in a comma-separated list.
Program to demonstrate extending interfaces:
interface Inter1 {
void meth1();
}
interface Inter2
{
void meth2();
}
interface Inter3 extends Inter1,Inter2 {
void meth3();
}
class OurClass implements Inter3 {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class InterfaceExtend {
public static void main(String[] args) {
Inter3 x = new OurClass();
x.meth1();
x.meth2();
x.meth3();
}
}
Output:
Packages:
• A package is generally a collection of classes and interfaces
• It provides a unique namespace for the classes, to avoid naming conflictions.
• Declaration of package statement resides at the top of a Java source file.
• A package can contain the following.
– Classes
– Interfaces
– Enumerated types
– Annotations
• Class that reside inside a package cannot be referred by their own name alone.
• The package name has to precede the name of the class, which is known as fully qualified name.
• If the package keyword is not used in any class for mentioning the name of the package, then it
becomes part of the default/unnamed package.
• So, the main purpose of packages is to provide a contextual namespace within which a class
resides.
• Java provides a syntax for package names
– Package names always in small letters and the words in the package name are separated
by periods.
– Ex: org.financial.inventory;
• Packages also provide a specific scope, known as package scope. All the classes defined in the
package can share the members declared without any access specifier.
Categories of Packages
The Java Packages are categorized into two categories (i) Java API Packages (ii) User Defined
Packages.
1. Java API Packages –Java API provides large number of classes grouped into different packages
according to the functionality. Most of the time we use the package available with Java API.
• Java run-time-system should know where to look for packages that you create?
• The answer has two parts.
• First, by default, the Java run-time system uses the current working directory as its starting
point. Thus, if your package is in the current directory, or a subdirectory of the current directory,
it will be found.
• Second, you can specify a directory path or paths by setting the CLASSPATH environmental
variable.
• The .class file in the above example is created in the directory path:
D:\javalab\com\aditya\demo\Circle.class
Here D:\javalab -- base directory path.
com\aditya\demo -- package directory path.
• Now the base directory path is need to store in CLASSPATH environment variable
STEP-5 : importing the class defined in a package, in another class defined in other package.
ImportTest.java
Output:
Class1.java
Output:
b) With in the scope of sub class in the same package:
Output:
Output:
d) With in the scope of sub class in the other package:
Output:
Output:
java.lang. package:
java.lang is a special package, as it is imported by default in all the classes that we create.
There is no need to explicitly import the lang package.
It contains the classes that form the basic building blocks of Java.
Some of the important classes from this package are:
o Object class
o Math class
o String class
o StringBuffer class
o Wrapper classes - Boolean, Integer, Long, Float, Double etc.,
o Exception classes - ArithmeticException, ArrayIndexOutOfBoundsException etc.,
o System, Process, Runtime classes
o Thread class
java.lang.Object Class
Object class is the parent of all the classes (predefined and user-defined) in Java.
For all the classes that we have created so far or will be creating further, Object class is the
parent by default and there is no need to explicitly inherit the Object class.
Methods in Object class:
java.lang.String class:
Strings are basically immutable objects in Java.
Immutable means once created, the strings cannot be changed.
Whenever we create strings, it is this class that is instantiated.
In Java, strings can be instantiated in two ways:
String x = "Hello";
String y = new String ("Hello");
When a string object is created from assigning a string literal, the object is created in String
intern pool.
When a string object is created with constructor, then the object is created in heap memory.
Equality of two strings are checked in two ways
Using equals() method: This method returns true if both strings have same content.
Using == (equality operator) : this operator checks whether both strings have same hashcode.
java.lang.Math Class
Math class is static class. It contains all static methods to perform mathematical operations.
Wrapper classes:
Java contains some data structures which won't accept to store primitive data types.
Then we have to take support of some classes to convert primitive data types in to class objects.
These classes are known as wrapper classes.
List of Wrapper classes are:
Exception Handling
What is exception?
• An exception (or exceptional event) is a problem that arises during the execution of a program.
• When an Exception is occurred, the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended.
• Therefore, these exceptions are to be handled.
Examples for Exceptions:
• Divide by zero Ex: 12/0
• Negative array size Ex: int[] a = new int[ -10];
• Index of array element is more than the size Ex: int[] arr = new int[5]; arr[10] = 25;
• File not found physically in the memory when going to read
• Network connection failed etc.,
Program to demonstrate about exception:
Output:
Case 1: Normal Execution
Case 2: Exception raised
Types of exceptions:
• An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM has
run out of memory.
• Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
• Based on these, we have three categories of Exceptions. You need to understand them to know
how exception handling works in Java.
• Checked exceptions − A checked exception is an exception that occurs at the compile time,
these are also called as compile time exceptions.
• Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions.
• Errors − These are not exceptions at all, but problems that arise beyond the control of the user
or the programmer.
Exception Hierarchy
• All exception classes are subtypes of the java.lang.Exception class.
• The exception class is a subclass of the Throwable class.
• Other than the exception class there is another subclass called Error which is derived from the
Throwable class.
• Errors are abnormal conditions that happen in case of severe failures, these are not handled by
the Java programs.
• Errors are generated to indicate errors generated by the runtime environment.
Some Built-in Exceptions:
1. If exception occurs in try block’s body then control immediately transferred(skipping rest of the
statements in try block) to the catch block. Once catch block finished execution then finally
block and after that rest of the program.
2. If there is no exception occurred in the code which is present in try block then first, the try block
gets executed completely and then control gets transferred to finally block (skipping catch
blocks).
3. If a return statement is encountered either in try or catch block. In this case finally block runs.
Control first jumps to finally and then it returned back to return statement
Output:
Case 1: normal execution:
Output:
Throw Statement:
• The throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception.
• The throw keyword is normally used to throw custom exception.
Throws clause:
• As we know that there are two types of exception checked and unchecked.
• Checked exception (compile time) force you to handle them, if you don’t handle them then the
program will not compile.
• When a method has statements prone to generate checked exceptions, the programmer has
two choices:
the checked exception has to be handled with in same method.
Otherwise the unhandled exception is listed in the throws clause
• points to remember about throws keyword:
throws keyword is required only for checked exception.
throws keyword is required only to convince compiler and usage of throws
keyword does not prevent abnormal termination of program.
By the help of throws keyword we can provide information to the caller of the
method about the exception.
Program to demonstrate throws keyword:
Output:
• You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the RuntimeException class.
Program to demonstrate user defined exception:
import java.util.Scanner;
class NotEligibleException extends Exception {
public String toString() {
return "You are not eligible for voting..";
}
}
class ThrowDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try
{
System.out.print("Enter your age : ");
int age = sc.nextInt();
if(age < 18)
{
throw new NotEligibleException();
} else {
System.out.println("Welcome! You are eligible for voting!");
}
}
catch (NotEligibleException ne)
{
System.out.println(ne);
}
}
}
Output:
Case 1:
Case 2 :
Assertions:
• Assertions are statements, used to test a condition is fulfilled or not.
• Generally assertions are used in testing phase only.
Program to demonstrate assertions:
Output:
Note: When working with assertions, we need to include the option -ea along with java
command.
List of questions asked in previous question papers:
Part-A
a) What happens when there is no suitable try block to handle exception?
b) Why to use finally block in java exception handling.
c) How java supports multiple inheritance?
d) Explain about the importance of extend and implement keywords.
e) Differentiate class, abstract class and interface.
f) Give the basic keywords used in exception handling.
h) How to create and use a package in Java program?
i) What is an assertion? What is its use in programming?
j) What is abstract class? Discuss with example.
k) What is the difference between an interface and an abstract class?
l) "Abstract classes can be defined without any abstract methods" - support this statement with
proper reasoning.
Part-B
1. a) Write an example program to show the calling sequence of constructors.
b) How to create packages and use them in java?
2. a) What is an exception? Explain exception handling in java with examples.
b) Write a program to implement multiple inheritances.
3. Give a detail note on interfaces and packages in java with examples.
4. What is inheritance? Explain in detail inheritance in java with examples.
5. a) Differentiate method overloading with method overriding with examples.
b) What is interface? How to create it and access it? Explain with example.
6. a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) How to handle multiple catch blocks for a nested try block? Explain with an example.
7. a) Explain multilevel inheritance with the help of abstract class in your program.
b) How to define a user exception in a program? Illustrate with an example.
8. a) How Packages differ from Interfaces? Explain it with a suitable example program to
calculate student marks statement.
b) What is an exception? How are exceptions handled in Java programming? Explain
9. What are the benefits of inheritance? Explain various forms of inheritance with suitable code
segments.
10. a) What are different types of inheritances? Discuss with examples for each.
.b) Write short notes on Java built in exceptions and chained exceptions.
11. a) What are the different forms of inheritance? Explain.
b) What are the various types of exceptions available in Java? Also discuss on how they are handled?
12. b) Explain various access specifies supported by Java with an example
13. a) Explain Creating Packages and Accessing a Package with examples.
b) Write a Java program to find the area and perimeter of square and circle using interface
14. a) Explain about Exception Handling in Java with examples.
b) Explain how final keyword is used to prevent overriding and inheritance.
15. What is meant by access protection? Explain different access specifiers supported by Java with
an example of each.
16. a) What is the use of super keyword in Java? Explain in detail.
b) What is the importance of abstract classes? Show it with an example.
17. a)What is an interface? Explain the definition and implementation of interface in Java.
b) Explain usage of following words in exception handling: throw, throws, finally.
18. a) What is meant by multilevel hierarchy? Explain with an example program in Java.
b) Illustrate the concept of method overriding with an example program.
19. a) Define package? Explain the process of finding a package.
b) Write a short note on i) Nested Interfaces. ii) Difference between class and interfaces.
20. a) Write a program to illustrate the usage of try and catch blocks in Java.
b) What is CLASSPATH? Explain its role in finding packages.
21. a) What cautions need to be taken while importing Explain with an example program for importing
packages?
b) What is an exception? Write about the fundamentals of exception handling used in Java.
Java programming-assignment-3
Part-A
Part-B
Programs