KEMBAR78
unit-2JAvaoopscomcepts IITM inheritance.pptx
Inheritance in Java
unit2
1
Basics of Classes in Java
By. Ms Gargi Mukherjee
Contents
• Introduction to classes and objects in Java.
• Understand how some of the OO concepts learnt so
far are supported in Java.
• Understand important features in Java classes.
2
Introduction
• Java is a true Object Oriented language and therefore
the underlying structure of all Java programs is
classes.
• Anything we wish to represent in Java must be
encapsulated in a class that defines the “state” and
“behavior” of the basic program components known
as objects.
• Classes create objects and objects use methods to
communicate between them.
3
Classes
• A class is a user defined abstract datatype.
class Box { mybox
double width;
double length;
double depth;
} to create the object syntax
Box mybox=new Box( );
4
Widwidth=
10 ,length=
15,
Depth=12
Program to demonstrate working of a class
5
6
class Box {
double width; //declared variables
double length;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[ ]) {
Box mybox = new Box(); //an object mybox of the class box is created,new is
the keyword thru which it is created.
Box mybox1=new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.length = 20;
mybox.depth = 15;
mybox1.width = 20;
mybox1.length =30;
mybox1.depth = 45;
// compute volume of box
vol = mybox.width * mybox.length * mybox.depth;//(10*20*15)
Adding Methods(functions)
• A class with only data fields has no life.
Objects created by such a class cannot
respond to any messages.
• Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
• The general form of a method declaration is:
7
returntype MethodName (parameter-list)
{
Method-body;
}
Adding Methods to Class Circle
8
class Box {
double width;
double length;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * length * depth);
}
} Method Body
9
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.length = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.length = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume(); //function is going to get called
// display volume of second box
mybox2.volume();
}
}
W=10,l=20,
d=15
3,6,9
myobj2
myobj1
Now, volume() returns the volume of a
box.
class Box {
double width;
double length;
double depth;
// compute and return volume
double volume() {
return width * length * depth;
}
} 10
11
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.length = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.length = 6;
mybox2.depth = 9;
// get volume of first box
vol= mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parametrised method demo
class Box {
double width;
double length;
double depth;
// compute and return volume
double volume() {
return width * length * depth;
}
// sets dimensions of box
void setDim(double w, double h, double d) {
width = w;
length = h;
depth = d;
}
}
12
13
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 10);
mybox2.setDim(3, 3, 3);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
O/P
Volume is: 2000
Volume is: 27
Adding constructors to class
• Constructor has same name as that of its class.
• Constructors do not have return type not even void
• They are used to initialize object of the class, etc.
15
class Box {
double width;
double length;
double depth;
// efault constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
length = 10;
depth = 10;
}
Box(double w, double h, double d) {
width = w;
length = h;
depth = d;
}
// compute and return volume
double volume() {
return width * length * depth;
}
}
16
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 10);
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
O/P
Volume is: 2000
Volume is: 1000
this
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.length = h;
this.depth = d;
}
17
18
Use this to resolve naming collisions.
Box(double width, double length, double depth)
{
this.width = width;
this.length = length;
this.depth = depth;
}
19
class Stack {
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
// Push an item onto the stack
void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
20
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++)
mystack1.push(i);
for(int i=10; i<20; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop()); System.out.println("Stack in
mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
Summary
• Classes, objects, and methods are the basic
components used in Java programming.
• We have discussed:
• How to define a class
• How to create objects
• How to add data fields and methods to classes
• How to access data fields and methods to classes
21
22
Write a program to create a class Student with following
members:
Data members:
Sname
Class
Age
Methods:
Constructors
readVal()
showVal()
Create a separate class with main function defined in it .
Program should create 2 objects for the class Student.
Program to add two
distances
23
24
class Distance
{
int feet, inches;
Distance()
{
feet=inches=0;
}
Distance(int x)
{
feet=inches=x;
}
Distance(int x1, int x2)
{
feet=x1;
inches=x2;
}
void addDistance(Distance di, Distance dj)
{
feet=di.feet+dj.feet;
inches=di.inches+dj.inches;
if(inches>=12)
{
feet=feet+(inches/12);
inches=(inches%12);
}
}
void show()
{
System.out.println("Feet = "+feet);
System.out.println("Inches = "+inches);
}
}
25
class DistanceDemo
{
public static void main(String args[])
{
Distance d1 =new Distance(5,12);
Distance d2 =new Distance(5,1);
Distance d3 =new Distance();
System.out.println("First Object Details are: ");
d1.show();
System.out.println("Second Object Details are: ");
d2.show();
d3.addDistance(d1,d2);
System.out.println("Third Object Details are: ");
d3.show();
}
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
26
27
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Inheritance
28
Why Do We Need Java Inheritance?
• Code Reusability: The code written in the
Superclass is common to all subclasses. Child
classes can directly use the parent class code.
• Method Overriding: Method Overriding is
achievable only through Inheritance. It is one of
the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we
do not have to provide all details, is achieved
through inheritance. Abstraction only shows the
functionality to the user.
29
Java Inheritance Types
• Below are the different types of inheritance which
are supported by Java.
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Multiple Inheritance(Using interfaces)
• Hybrid Inheritance
30
Single Inheritance
• In single inheritance, a sub-class is derived
from only one super class. It inherits the
properties and behavior of a single-parent
class. Sometimes, it is also known as simple
inheritance. In the below figure, ‘A’ is a
parent class and ‘B’ is a child class. The class
‘B’ inherits all the properties of the class ‘A’
31
32
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
33
class SimpleInheritance {
public static void main(String args[]) {
A a = new A();
B b = new B();
a.i = 10;
a.j = 20;
System.out.println("Contents of a: ");
a.showij();
System.out.println();
b.i = 7;
b.j = 8;
b.k = 9;
System.out.println("Contents of b: ");
b.showij();
b.showk();
System.out.println();
System.out.println("Sum of i, j and k in b:");
b.sum();
}
}
In Multilevel Inheritance
• A derived class will be inheriting a base
class, and as well as the derived class also
acts as the base class for other classes. In
the below image, class A serves as a base
class for the derived class B, which in turn
serves as a base class for the derived class
C. In Java, a class cannot directly access
the grandparent’s members.
34
• import java.io.*;
• import java.lang.*;
• import java.util.*;
• class One {
• public void print_gk() {
• System.out.println("Greet");
• }}
• class Two extends One {
• // Method to print "for"
• public void print_for() {
• System.out.println("for");
• }}
• class Three extends Two {
• public void print_lastgk() {
• System.out.println("Great");
• }}
• public class Main {
• public static void main(String[] args)
{
• // Creating an object of class
Three
• Three g = new Three();
•
• // Calling method from class One
• g.print_gk();
•
• // Calling method from class Two
• g.print_for();
•
• // Calling method from class
Three
• g.print_lastgk();
• }}
35
Hierarchical Inheritance
• In Hierarchical
Inheritance, one
class serves as a
superclass (base
class) for more than
one subclass. In the
below image, class
A serves as a base
class for the
derived classes B,
C, and D.
36
• class A {
• public void print_A()
{ System.out.println("Class A"); }
• }
• class B extends A {
• public void print_B()
{ System.out.println("Class B"); }
• }
• class C extends A {
• public void print_C()
{ System.out.println("Class C"); }
• }
• class D extends A {
• public void print_D()
{ System.out.println("Class D"); }
• }
• public class Test {
• public static void main(String[]
args)
• {
• B obj_B = new B();
• obj_B.print_A();
• obj_B.print_B();
• C obj_C = new C();
• obj_C.print_A();
• obj_C.print_C();
• D obj_D = new D();
• obj_D.print_A();
• obj_D.print_D();
• }
• }
37
Multiple Inheritance (Through Interfaces)
• In Multiple inheritances,
one class can have more
than one superclass and
inherit features from all
parent classes. Please note
that Java does not support
multiple inheritances with
classes. In Java, we can
achieve multiple
inheritances only through
Interfaces. In the image
below, Class C is derived
from interfaces A and B.
38
• // Java program to illustrate the
• // concept of Multiple inheritance
• import java.io.*;
• import java.lang.*;
• import java.util.*;
• interface One {
• public void print_gk();
• }
• interface Two {
• public void print_for();
• }
• interface Three extends One, Two {
• public void print_gk();
• }
• class Child implements Three {
• public void print_gk()
• { System.out.println("Great");
• }
• public void print_for()
{ System.out.println("for"); }
• }
• public class Main {
• public static void
main(String[] args)
• {
• Child c = new Child();
• c.print_gk();
• c.print_for();
• c.print_gk();
• }
• }
39
40
Class and its types of
constructors
 Default
 Parameterized
 Object as a Parameter
41
class Box {
double width;
double length;
double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
length = ob.length;
depth = ob.depth;
}
// constructor used when all dimensions
specified
Box(double w, double h, double d) {
width = w;
length = h;
depth = d;
}
// constructor used when no dimensions
specified
Box() {
width = -1; // use -1 to indicate
length = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = length = depth = len;
}
// compute and return volume
double volume() {
return width * length * depth;
}
}
42
class BoxWeight extends Box
{
double weight;
// constructor for BoxWeight with 4 arguments
BoxWeight(double w, double l, double d, double m)
{
width = w;
length = l;
depth = d;
weight = m;
}
}
43
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}
Use of super-The super keyword in Java is a reference
variable that is used to refer to parent class when we’re
working with objects.
44
45
class Box {
private double width;
private double length;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = ob.width;
length = ob.length;
depth = ob.depth;
}
// constructor used when all dimensions
specified
Box(double w, double l, double d) {
width = w;
length = l;
depth = d;
}
// constructor used when no dimensions
specified
Box() {
width = -1; // use -1 to indicate
length = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len) {
width = length = depth = len;
}
// compute and return volume
double volume() {
return width * length * depth;
}
}
46
// BoxWeight now fully implements all
constructors.
class BoxWeight extends Box
{
double weight;
// construct clone of an object
BoxWeight(BoxWeight ob)
{ // pass object to constructor
super(ob);
weight = ob.weight;
}
// constructor when all parameters are
specified
BoxWeight(double w, double l, double d,
double m) {
super(w, l, d); // call superclass 3 argument
constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
47
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20,
15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4,
0.076);
BoxWeight mybox3 = new BoxWeight(); //
default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new
BoxWeight(mybox1);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
System.out.println("Weight of mybox1 is " +
mybox1.weight);
System.out.println();
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " +
vol);
System.out.println("Weight of mybox2 is " +
System.out.println();
vol = mybox3.volume();
System.out.println("Volume of mybox3 is " +
vol);
System.out.println("Weight of mybox3 is " +
mybox3.weight);
System.out.println();
vol = myclone.volume();
System.out.println("Volume of myclone is " +
vol);
System.out.println("Weight of myclone is " +
myclone.weight);
System.out.println();
vol = mycube.volume();
System.out.println("Volume of mycube is " +
vol);
System.out.println("Weight of mycube is " +
mycube.weight);
System.out.println();
}
}
Order of constructor calling in Inheritance
48
49
// 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 CallingCons {
public static void main(String args[]) {
C c = new C();
50
O/P:
Inside A’s Constructor
Inside B’s Constructor
Inside C’s Constructor
Overridding Methods
51
52
// 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);
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
}
}
Another Style
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
} 53
Use of “abstract”
54
Abstract Classes
• Class containing one or more function as abstract is
known as abstract class and therefore its declaration
should be preceded with the keyword abstract.
• An Abstract class is a conceptual class.
• An Abstract class cannot be instantiated – objects cannot
be created.
• A class declared abstract, even with no abstract methods
can not be instantiated.
• A subclass of an abstract class can be instantiated if it
overrides all abstract methods by implementation them.
• A subclass that does not implement all of the superclass
abstract methods is itself abstract; and it cannot be
instantiated. 55
Abstract Class Syntax
abstract class ClassName
{
...
…
abstract Type MethodName1();
…
…
Type Method2()
{
// method body
}
}
• When a class contains one or more abstract methods, it should be declared as abstract class.
• The abstract methods of an abstract class must be defined in its subclass.
• We cannot declare abstract constructors or abstract static methods.
56
57
For eg:
abstract class Figure {
double dim1;
double dim2;
Figure(double a, double b) {
dim1 = a;
dim2 = b;
}
// area is now an an abstract method
abstract double area();
}
58
class Rectangle extends Figure {
Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure {
Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle
double area() {
System.out.println("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
59
class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); is illegal now
as it cannot be instantiated
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
System.out.println("Area is " + r.area());
System.out.println("Area is " + t.area());
}
}
Final Members: A way for Preventing
Overriding of Members in Subclasses
• All methods and variables can be overridden by
default in subclasses.
• This can be prevented by declaring them as final using
the keyword “final” as a modifier. For example:
• final int marks = 100;
• final void display();
• This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.
60
61
FINAL METHOD
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
FINAL CLASS
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Interfaces
62
Design Abstraction and a way for achieving Multiple
Inheritance
Interfaces
• Interface is a conceptual entity similar to a Abstract
class.
• Can contain only constants (final fields) and
abstract method. (no implementation) - Different
from Abstract classes.
• When number of classes share a common
interface each class should implement the
interface.
63
Features of an Interface
• An interface is basically a kind of class—it contains
methods and final fields.
• Therefore, it is the responsibility of the class that
implements an interface to supply the code for
methods.
• A class can implement any number of interfaces, but
cannot extend more than one class at a time.
• Therefore, interfaces are considered as an informal way
of realising multiple inheritance in Java.
64
Interface - Example
65
speak()
Politician Priest
<<Interface>>
Speaker
speak() speak()
Lecturer
speak()
Interfaces Definition
• Syntax (appears like abstract class):
• Example:
66
interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method
body
}
interface Speaker {
public void speak( );
}
Implementing Interfaces
• Interfaces are used like super-classes who properties
are inherited by classes. This is achieved by creating a
class that implements the given interface as follows:
67
class ClassName implements InterfaceName [, InterfaceName2, …]
{
// Body of Class
}
Implementing Interfaces
Example
68
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}
class Priest implements Speaker {
public void speak(){
System.out.println(“Religious Talks”);
}
}
class Lecturer implements Speaker {
public void speak(){
System.out.println(“Talks Object Oriented Design and
Programming!”);
}
}
Extending Interfaces
• Like classes, interfaces can also be extended.
The new sub-interface will inherit all the
members of the superinterface in the manner
similar to classes. This is achieved by using
the keyword extends as follows:
69
interface InterfaceName2 extends InterfaceName1
{
// Body of InterfaceName2
}
Inheritance and Interface
Implementation
• A general form of interface implementation:
• This shows a class can extended another class while implementing
one or more interfaces. It appears like a multiple inheritance (if
we consider interfaces as special kind of classes with certain
restrictions or special features).
70
class ClassName extends SuperClass implements InterfaceName [,
InterfaceName2, …]
{
// Body of Class
}
71
/* An example Java Program to demontrate
the working of an Interface*/
interface Shape
{
float PI=3.14f;
float computeArea();
}
class Circle implements Shape
{
float radius;
Circle (float r)
{
radius=r;
}
public float computeArea()
{
return PI*radius*radius;
}
}
class IntfTest
{
public static void main(String args[])
{
Circle c1=new Circle(7.0f);
float ar=0.0f;
ar=c1.computeArea();
System.out.println("Area is = "+ar);
}
}
72
Java 8 Default Methods
Interfaces in Java always contained method declaration not
their definitions (method body). There was no way of
defining method body / definition in interfaces. This is
because historically Java didn’t allow multiple inheritance of
classes. It allowed multiple inheritance of interfaces as
interface were nothing but method declaration. This solves
the problem of ambiguity in multiple inheritance. Since Java
8 has a new feature called Default Methods. It is now
possible to add method bodies into interfaces!
73
public interface Math
int add(int a, int b);
default int multiply(int a, int b)
{
return a * b;
}
}
n above Math interface we added a method
multiply with actual method body.
74
Why we need Default Methods?
or
Why would one want to add methods into
Interfaces?
We’ll it is because interfaces are too tightly coupled
with their implementation classes. i.e. it is not
possible to add a method in interface without
breaking the implementer class. Once you add a
method in interface, all its implemented classes must
declare method body of this new method.
75
What about Multiple Inheritance?
Adding method definitions in interfaces can add ambiguity in multiple inheritance.
isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider
below example:
interface Person
{
default void sayHello()
{
System.out.println("Hello");
}
}
interface Male
{
default void sayHello()
{
System.out.println("Hi");
}
}
class Sam implements Person, Male
{
}
76
In this example we have same defender method sayHello in
both interfaces Person and Male. Class Sam implements these
interfaces. So which version of sayHello will be inherited?
We’ll if you try to compile this code in Java 8, it will give
following error.
class Sam inherits unrelated defaults for sayHello() from
types Person and Male class Sam implements Person,
Male { ^ 1 error
So that solves multiple inheritance problem. You cannot
implement multiple interfaces having same signature of Java 8
default methods (without overriding explicitly in child class).
77
We can solve the above problem by overriding sayHello method
in class Sam.
interface Person
{
default void sayHello()
{
System.out.println("Hello");
}
}
interface Male
{
default void sayHello()
{
System.out.println("Hi");
}
}
class Sam implements Person, Male
{
void sayHello() //override the sayHello to resolve ambiguity
{
}
}
78
It is also possible to explicitly call method from child
class to parent interface. Consider in above example
you want to call sayHello method from Male interface
when Sam.sayHello is called. You can use super keyword
to explicitly call the appropriate method.
class Sam implements Person, Male
{
//override the sayHello to resolve ambiguity
void sayHello()
{
Male.super.sayHello();
}
}
Package
a
Collection of Classes $ Interfaces bundled together
Ms Gargi Mukherjee
79
80
Introduction
• The main feature of OOP is its ability to support the reuse of
code:
• Extending the classes (via inheritance)
• Extending interfaces
• The features in basic form limited to reusing the classes within
a program.
• What if we need to use classes from other programs without
physically copying them into the program under development ?
• In Java, this is achieved by using what is known as “packages”,
a concept similar to “class libraries” in other languages.
Packages
• Packages are Java’s way of grouping a number of related classes
and/or interfaces together into a single unit. That means,
packages act as “containers” for classes.
• The benefits of organising classes into packages are:
• The classes contained in the packages of other programs/ applications
can be reused.
• In packages classes can be unique compared with classes in other
packages. That is two classes in two different packages can have the
same name. If there is a naming clash, then classes can be accessed with
their fully qualified name.
• Classes in packages can be hidden if we don’t want other packages to
access them.
• Packages also provide a way for separating “design” from coding.
81
82
Java Foundation Packages
• Java provides a large number of classes groped into different packages
based on their functionality.
• The six foundation Java packages are:
• java.lang
• Contains classes for primitive types, strings, math functions, threads, and
exception
• java.util
• Contains classes such as Random, Vector,Collections, hash tables, date etc.
• java.io
• Stream classes for I/O
• java.awt
• Classes for implementing GUI – windows, buttons, menus etc.
• java.net
• Classes for networking
• java.applet
• Classes for creating and implementing applets
83
Using System Packages
• The packages are organised in a hierarchical
structure. For example, a package named “java”
contains the package “awt”, which in turn contains
various classes required for implementing GUI
(graphical user interface).
84
Graphics
Font
java
Image
…
awt
lang “java” Package containing
“lang”, “awt”,.. packages;
Can also contain classes.
awt Package containing
classes
Classes containing
methods
Accessing Classes from Packages
• There are two ways of accessing the classes stored in
packages:
• Using fully qualified class name
• java.lang.Math.sqrt(x);
• Import package and use class name directly.
• import java.lang.Math
• Math.sqrt(x);
• Selected or all classes in packages can be imported:
• Implicit in all programs: import java.lang.*;
• package statement(s) must appear first
85
import package.class;
import package.*;
Creating Packages
• Java supports a keyword called “package” for creating user-
defined packages. The package statement must be the first
statement in a Java source file (except comments and white
spaces) followed by one or more classes.
• Package name is “myPackage” and classes are considred as part
of this package; The code is saved in a file called “ClassA.java”
and located in a directory called “myPackage”.
86
package myPackage;
public class ClassA {
// class body
}
class ClassB {
// class body
}
Creating Sub Packages
• Classes in one ore more source files can be part of
the same packages.
• As packages in Java are organised
hierarchically, sub-packages can be created as
follows:
• package myPackage.Math
• package myPackage.secondPakage.thirdPackage
• Store “thirdPackage” in a subdirectory named
“myPackagesecondPackage”. Store
“secondPackage” and “Math” class in a subdirectory
“myPackage”.
87
Accessing a Package
• As indicated earlier, classes in packages can
be accessed using a fully qualified name or
using a short-cut as long as we import a
corresponding package.
• The general form of importing package is:
• import package1[.package2][…].classname
• Example:
• import myPackage.ClassA;
• import myPackage.secondPackage
• All classes/interfaces from higher-level package
can be imported as follows:
• import myPackage.*;but it does’nt mean we have
imported all other sub packages of mypackage.
88
Using a Package
• Let us store the code listing below in a file named
“ClassA.java” within subdirectory named
“myPackage” within the current directory (say “bin”).
89
package myPackage;
public class ClassA {
// class body
public void display()
{
System.out.println("Hello, I am ClassA");
}
}
class ClassB {
// class body
}
Using a Package
• Within the current directory (“bin”) store the
following code in a file named “ClassX.java”
90
import myPackage.ClassA;
public class ClassX
{
public static void main(String args[])
{
ClassA objA = new ClassA();
objA.display();
}
}
Compiling and Running
• When ClassX.java is compiled, the compiler
compiles it and places .class file in current directly.
If .class of ClassA in subdirectory “myPackage” is
not found, it compiles ClassA also.
• Note: It does not include code of ClassA into
ClassX
• When the program ClassX is run, java loader looks
for ClassA.class file in a package called
“myPackage” and loads it.
91
92
Using a Package
• Let us store the code listing below in a file named
“ClassA.java” within subdirectory named
“secondPackage” within the current directory (say
“abc”).
93
package secondPackage;
public class ClassC {
// class body
public void display()
{
System.out.println("Hello, I am ClassC");
}
}
Using a Package
• Within the current directory (“abc”) store the
following code in a file named “ClassX.java”
94
import myPackage.ClassA;
import secondPackage.ClassC;
public class ClassY
{
public static void main(String args[])
{
ClassA objA = new ClassA();
ClassC objC = new ClassC();
objA.display();
objC.display();
}
}
Output
java ClassY
Hello, I am ClassA
Hello, I am ClassC
95
Protection and Packages
• All classes (or interfaces) accessible to all others in
the same package.
• Class declared public in one package is accessible
within another. Non-public class is not
• Members of a class are accessible from a difference
class, as long as they are not private
• protected members of a class in a package are
accessible to subclasses in a different class
96
Visibility - Revisited
• Public keyword applied to a class, makes it
available/visible everywhere. Applied to a method or
variable, completely visible.
• Private fields or methods for a class only visible within
that class. Private members are not visible within
subclasses, and are not inherited.
• Protected members of a class are visible within the class,
subclasses and also within all classes that are in the same
package as that class.
97
Visibility Modifiers
98
Accessible to: public protected Package
(default)
private
Same Class Yes Yes Yes Yes
Class in package Yes Yes Yes No
Subclass in
different package
Yes Yes No No
Non-subclass
different package
Yes No No No
Access Modifiers in Java
• There are two types of modifiers in Java: access modifiers and non-access modifiers.
• The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
• There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
Private
The private access modifier is accessible only within the class.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Default
• If you don't use any modifier, it is treated as default by
default. The default modifier is accessible only within
package. It cannot be accessed from outside the
package. It provides more accessibility than private.
But, it is more restrictive than protected, and public.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
• The protected access modifier is accessible within package
and outside the package but through inheritance only.
• The protected access modifier can be applied on the data
member, method and constructor. It can't be applied on the
class.
• It provides more accessibility than the default modifer.
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Public
• The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Adding a Class to a Package
• Consider an existing package that contains a
class called “Teacher”:
• This class is stored in “Teacher.java” file
within a directory called “pack1”.
• How do we a new public class called
“Student” to this package.
10
6
package pack1;
public class Teacher
{
// class body
}
Adding a Class to a Package
• Define the public class “Student” and place the package
statement before the class definition as follows:
• Store this in “Student.java” file under the directory “pack1”.
• When the “Student.java” file is compiled, the class file will
be created and stored in the directory “pack1”. Now, the
package “pack1” will contain both the classes “Teacher”
and “Student”.
10
7
package pack1;
public class Student
{
// class body
}
class Teacher
package pack1;
class Student
Packages and Name Clashing
• When packages are developed by different
organizations, it is possible that multiple packages
will have classes with the same name, leading to name
classing.
• We can import and use these packages like:
• import pack1.*;
• import pack2.*;
• Student student1; // Generates compilation error
10
8
class Teacher
package pack1;
class Student
class Student
package pack2;
class Courses
Handling Name Clashing
• In Java, name classing is resolved by accessing classes with
the same name in multiple packages by their fully qualified
name.
• Example:
import pack1.*;
import pack2.*;
pack1.Student student1;
pack2.Student student2;
Teacher teacher1;
Courses course1;
10
9
Extending a Class from Package
• A new class called “Professor” can be created by
extending the “Teacher” class defined the package
“pack1” as follows:
11
0
import pack1.Teacher;
public class Professor extends Teacher
{
// body of Professor class
// It is able to inherit public and protected members,
// but not private or default members of Teacher class.
}
Summary
• Packages allow grouping of related classes into a
single united.
• Packages are organised in hierarchical structure.
• Packages handle name classing issues.
• Packages can be accessed or inherited without actual
copy of code to each program.
11
1
Exception Handling in java
By Gargi Mukherjee
Exceptions
Exception are such anomalous conditions (or typically an event)
which changes the normal flow of execution of a program.
Exceptions are used for signaling erroneous (exceptional)
conditions which occur during the run time processing. Exceptions
may occur in any programming language.
Java Exception is an object that describes
an exceptional condition that has occurred
in a piece of code.
When exception takes place, an object
representing that condition is created and
thrown in the method that caused the
error. Then this exception is caught and
processed.
Advantages of exception handling
1. Exception provides the means to separate the details of what to do when something
out of the ordinary happens from the main logic of a program.
2. With the help of this mechanism the working code and the error-handling code can
be disintegrated. It also gives us the scope of organizing and differentiating between
different error types using a separate block of codes. This is done with the help of
try-catch blocks.
3. Furthermore the errors can be propagated up the method call stack i.e. problems
occurring at the lower level in the chain can be handled by the methods higher up the
call chain .
Types of Exceptions
Exception class is used for exceptional conditions that user
programs should catch. This is also the class that you will
subclass to create your own custom exception types. There
is an important subclass of Exception, called
RuntimeException. Exceptions of this type are
automatically defined for the programs that you write and
include things such as division by zero and invalid array
indexing.
Error class defines exceptions that are not expected to be
caught under normal circumstances by your program.
Exceptions of type Error are used by the Java run-time
system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an
error.
Note: This chapter will not be dealing with exceptions of type Error,
because these are typically created in response to catastrophic
failures that cannot usually be handled by your program.
Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
Program statements that we want to monitor for
exceptions are contained within a try block. If an
exception occurs within the try block, it is
thrown. Our code can catch this exception
(using catch) and handle it in some rational
manner. System-generated exceptions are
automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword
throw. Any exception that is thrown out of a
method must be specified as such by a throws
clause. Any code that absolutely must be executed
before a method returns is put in a finally block.
This is the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
finally {
// block of code to be executed before try block
ends
}
Here, ExceptionType is the type of exception that has
occurred.
Uncaught Exceptions
Before you learn how to handle exceptions in
your program, it is useful to see what happens
when you don’t handle them. This small
program includes an expression that
intentionally causes a divide-by-zero error.
class Exc
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by
zero, it constructs a new exception object and then throws this
exception. This causes the execution of Exc to stop, because
once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately. In this example, we
haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java
run-time system. Any exception that is not caught by your program
will ultimately be processed by the default handler. The default
handler displays a string describing the exception, prints a stack
trace from the point at which the exception occurred, and
terminates the program.
Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero
at Exc.main(Exc0.java:4)
Using try and catch
Although the default exception handler
provided by the Java run-time system is
useful for debugging, we will usually
want to handle an exception yourself.
Doing so
provides two benefits.
First, it allows you to fix the error.
Second, it prevents the program from
automatically terminating.
To guard against and handle a run-
time error, simply enclose the code
that you
want to monitor inside a try block.
Immediately following the try
block, include a catch clause that
specifies the exception type that
you wish to catch.
class Exc2
{
public static void main(String args[])
{
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Catch is not a function
Notice that the call to println( ) inside the try block is never
executed. Once an exception is thrown, program control transfers
out of the try block into the catch block.
Put differently, catch is not “called,” so execution never “returns”
to the try block from a catch. Thus, the line “This will not be
printed.” is not displayed. Once the catch statement has executed,
program control continues with the next line in the program following
the entire try/catch mechanism.
Multiple Catch Clauses
In some cases, more than one exception could be
raised by a single piece of code. To handle this type of
situation, we can specify two or more catch clauses,
each catching a different type of exception. When an
exception is thrown, each catch statement is
inspected in order, and the first one whose type
matches that of the exception is executed. After one
catch statement executes, the others are bypassed,
and execution continues after the try/catch block.
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
This program will cause a division-by-zero exception if it is started with
no commandline parameters, since a will equal zero. It will survive the
division if you provide a command-line argument, setting a to
something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of
1, yet the program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
Java’s Built-in Exceptions
Unchecked Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalMonitorStateException Illegal monitor operation, such as
waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect
state.
IllegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
Checked Exception
Throw- Java throw keyword is used to throw an exception
explicitly.
We can throw either checked or unchecked exceptions in Java by throw
keyword. It is mainly used to throw a custom exception. A snippet
below
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundExcept
ion {
FileReader file = new FileReader("C:UsersAnurati
Desktopabc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
throws
If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that callers of the
method can guard themselves against that exception. You do
this by including a throws clause in the method’s
declaration. A throws clause lists the types of exceptions that
a method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of
their subclasses. All other exceptions that a method can throw
must be declared in the throws clause. If they are not, a
compile-time error will result.
This is the general form of a method declaration that includes a
throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
Following is an example of an incorrect program
that tries to throw an exception that it does not
catch. Because the program does not specify a
throws clause to declare this fact, the program
will not compile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, you need to make two changes. First, you need
to declare that throwOne( ) throws IllegalAccessException. Second, main( )
must definea try/catch statement that catches this exception.
The corrected example is shown here:
// This is now correct.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
}
catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
Throw and throws
• 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
Java Nested try block
• In Java, using a try block inside another try block is
permitted. It is called as nested try block. Every
statement that we enter a statement in try block,
context of that exception is pushed onto the stack.
• For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the
outer try block can handle the ArithemeticException
(division by zero).
• /main try block
• try
• {
• statement 1;
• statement 2;
• //try catch block within another try
block
• try
• {
• statement 3;
• statement 4;
• //try catch block within nested try block
• try
• {
• statement 5;
• statement 6;
• }
• catch(Exception e2)
• {
• //exception message
• }
•
• }
• catch(Exception e1)
• {
• //exception message
• }
• }
• //catch block of parent (outer) try
block
• catch(Exception e3)
• {
• //exception message
• }
• ....
finally
When exceptions are thrown, execution in a method takes a rather abrupt,
nonlinear path that alters the normal flow through the method. Depending upon
how themethod is coded, it is even possible for an exception to cause the
method to return prematurely. This could be a problem in some methods. For
example, if a method opens a file upon entry and closes it upon exit, then you
will not want the code that closes the file to be bypassed by the exception-
handling mechanism. The finally keyword is designed to address this
contingency.
finally creates a block of code that will be executed after a try/catch block
has completed and before the code following the try/catch block. The finally
block will execute whether or not an exception is thrown. If an exception is
thrown, the finally block will execute even if no catch statement matches the
exception. Any time a
method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing file
handles and freeing up any other resources that might have been allocated at
the beginning of a method with the intent of disposing of them before returning.
The finally clause is optional.
class FinallyDemo {
// Through an exception out of the
method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC() {
try {
System.out.println("inside procC");
} finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}
Here is the output generated by the preceding
program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{
try {
compute(1);
compute(20);
} catch (MyException e)
{ System.out.println("Caught " + e);
}
} }
OUTPUT
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

unit-2JAvaoopscomcepts IITM inheritance.pptx

  • 1.
    Inheritance in Java unit2 1 Basicsof Classes in Java By. Ms Gargi Mukherjee
  • 2.
    Contents • Introduction toclasses and objects in Java. • Understand how some of the OO concepts learnt so far are supported in Java. • Understand important features in Java classes. 2
  • 3.
    Introduction • Java isa true Object Oriented language and therefore the underlying structure of all Java programs is classes. • Anything we wish to represent in Java must be encapsulated in a class that defines the “state” and “behavior” of the basic program components known as objects. • Classes create objects and objects use methods to communicate between them. 3
  • 4.
    Classes • A classis a user defined abstract datatype. class Box { mybox double width; double length; double depth; } to create the object syntax Box mybox=new Box( ); 4 Widwidth= 10 ,length= 15, Depth=12
  • 5.
    Program to demonstrateworking of a class 5
  • 6.
    6 class Box { doublewidth; //declared variables double length; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[ ]) { Box mybox = new Box(); //an object mybox of the class box is created,new is the keyword thru which it is created. Box mybox1=new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.length = 20; mybox.depth = 15; mybox1.width = 20; mybox1.length =30; mybox1.depth = 45; // compute volume of box vol = mybox.width * mybox.length * mybox.depth;//(10*20*15)
  • 7.
    Adding Methods(functions) • Aclass with only data fields has no life. Objects created by such a class cannot respond to any messages. • Methods are declared inside the body of the class but immediately after the declaration of data fields. • The general form of a method declaration is: 7 returntype MethodName (parameter-list) { Method-body; }
  • 8.
    Adding Methods toClass Circle 8 class Box { double width; double length; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * length * depth); } } Method Body
  • 9.
    9 class BoxDemo3 { publicstatic void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.length = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.length = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); //function is going to get called // display volume of second box mybox2.volume(); } } W=10,l=20, d=15 3,6,9 myobj2 myobj1
  • 10.
    Now, volume() returnsthe volume of a box. class Box { double width; double length; double depth; // compute and return volume double volume() { return width * length * depth; } } 10
  • 11.
    11 class BoxDemo4 { publicstatic void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.length = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.length = 6; mybox2.depth = 9; // get volume of first box vol= mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
  • 12.
    Parametrised method demo classBox { double width; double length; double depth; // compute and return volume double volume() { return width * length * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w; length = h; depth = d; } } 12
  • 13.
    13 class BoxDemo5 { publicstatic void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 10); mybox2.setDim(3, 3, 3); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } O/P Volume is: 2000 Volume is: 27
  • 14.
    Adding constructors toclass • Constructor has same name as that of its class. • Constructors do not have return type not even void • They are used to initialize object of the class, etc.
  • 15.
    15 class Box { doublewidth; double length; double depth; // efault constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; length = 10; depth = 10; } Box(double w, double h, double d) { width = w; length = h; depth = d; } // compute and return volume double volume() { return width * length * depth; } }
  • 16.
    16 class BoxDemo7 { publicstatic void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 10); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } } O/P Volume is: 2000 Volume is: 1000
  • 17.
    this // A redundantuse of this. Box(double w, double h, double d) { this.width = w; this.length = h; this.depth = d; } 17
  • 18.
    18 Use this toresolve naming collisions. Box(double width, double length, double depth) { this.width = width; this.length = length; this.depth = depth; }
  • 19.
    19 class Stack { intstck[] = new int[10]; int tos; // Initialize top-of-stack Stack() { tos = -1; } // Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else
  • 20.
    20 class TestStack { publicstatic void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack(); // push some numbers onto the stack for(int i=0; i<10; i++) mystack1.push(i); for(int i=10; i<20; i++) mystack2.push(i); // pop those numbers off the stack System.out.println("Stack in mystack1:"); for(int i=0; i<10; i++) System.out.println(mystack1.pop()); System.out.println("Stack in mystack2:"); for(int i=0; i<10; i++) System.out.println(mystack2.pop()); } }
  • 21.
    Summary • Classes, objects,and methods are the basic components used in Java programming. • We have discussed: • How to define a class • How to create objects • How to add data fields and methods to classes • How to access data fields and methods to classes 21
  • 22.
    22 Write a programto create a class Student with following members: Data members: Sname Class Age Methods: Constructors readVal() showVal() Create a separate class with main function defined in it . Program should create 2 objects for the class Student.
  • 23.
    Program to addtwo distances 23
  • 24.
    24 class Distance { int feet,inches; Distance() { feet=inches=0; } Distance(int x) { feet=inches=x; } Distance(int x1, int x2) { feet=x1; inches=x2; } void addDistance(Distance di, Distance dj) { feet=di.feet+dj.feet; inches=di.inches+dj.inches; if(inches>=12) { feet=feet+(inches/12); inches=(inches%12); } } void show() { System.out.println("Feet = "+feet); System.out.println("Inches = "+inches); } }
  • 25.
    25 class DistanceDemo { public staticvoid main(String args[]) { Distance d1 =new Distance(5,12); Distance d2 =new Distance(5,1); Distance d3 =new Distance(); System.out.println("First Object Details are: "); d1.show(); System.out.println("Second Object Details are: "); d2.show(); d3.addDistance(d1,d2); System.out.println("Third Object Details are: "); d3.show(); }
  • 26.
    class OverloadDemo { voidtest() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } 26
  • 27.
    27 class Overload { publicstatic void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }
  • 28.
  • 29.
    Why Do WeNeed Java Inheritance? • Code Reusability: The code written in the Superclass is common to all subclasses. Child classes can directly use the parent class code. • Method Overriding: Method Overriding is achievable only through Inheritance. It is one of the ways by which Java achieves Run Time Polymorphism. • Abstraction: The concept of abstract where we do not have to provide all details, is achieved through inheritance. Abstraction only shows the functionality to the user. 29
  • 30.
    Java Inheritance Types •Below are the different types of inheritance which are supported by Java. • Single Inheritance • Multilevel Inheritance • Hierarchical Inheritance • Multiple Inheritance(Using interfaces) • Hybrid Inheritance 30
  • 31.
    Single Inheritance • Insingle inheritance, a sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. Sometimes, it is also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the class ‘A’ 31
  • 32.
    32 class A { inti, j; void showij() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } }
  • 33.
    33 class SimpleInheritance { publicstatic void main(String args[]) { A a = new A(); B b = new B(); a.i = 10; a.j = 20; System.out.println("Contents of a: "); a.showij(); System.out.println(); b.i = 7; b.j = 8; b.k = 9; System.out.println("Contents of b: "); b.showij(); b.showk(); System.out.println(); System.out.println("Sum of i, j and k in b:"); b.sum(); } }
  • 34.
    In Multilevel Inheritance •A derived class will be inheriting a base class, and as well as the derived class also acts as the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members. 34
  • 35.
    • import java.io.*; •import java.lang.*; • import java.util.*; • class One { • public void print_gk() { • System.out.println("Greet"); • }} • class Two extends One { • // Method to print "for" • public void print_for() { • System.out.println("for"); • }} • class Three extends Two { • public void print_lastgk() { • System.out.println("Great"); • }} • public class Main { • public static void main(String[] args) { • // Creating an object of class Three • Three g = new Three(); • • // Calling method from class One • g.print_gk(); • • // Calling method from class Two • g.print_for(); • • // Calling method from class Three • g.print_lastgk(); • }} 35
  • 36.
    Hierarchical Inheritance • InHierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below image, class A serves as a base class for the derived classes B, C, and D. 36
  • 37.
    • class A{ • public void print_A() { System.out.println("Class A"); } • } • class B extends A { • public void print_B() { System.out.println("Class B"); } • } • class C extends A { • public void print_C() { System.out.println("Class C"); } • } • class D extends A { • public void print_D() { System.out.println("Class D"); } • } • public class Test { • public static void main(String[] args) • { • B obj_B = new B(); • obj_B.print_A(); • obj_B.print_B(); • C obj_C = new C(); • obj_C.print_A(); • obj_C.print_C(); • D obj_D = new D(); • obj_D.print_A(); • obj_D.print_D(); • } • } 37
  • 38.
    Multiple Inheritance (ThroughInterfaces) • In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B. 38
  • 39.
    • // Javaprogram to illustrate the • // concept of Multiple inheritance • import java.io.*; • import java.lang.*; • import java.util.*; • interface One { • public void print_gk(); • } • interface Two { • public void print_for(); • } • interface Three extends One, Two { • public void print_gk(); • } • class Child implements Three { • public void print_gk() • { System.out.println("Great"); • } • public void print_for() { System.out.println("for"); } • } • public class Main { • public static void main(String[] args) • { • Child c = new Child(); • c.print_gk(); • c.print_for(); • c.print_gk(); • } • } 39
  • 40.
    40 Class and itstypes of constructors  Default  Parameterized  Object as a Parameter
  • 41.
    41 class Box { doublewidth; double length; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; length = ob.length; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; length = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate length = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = length = depth = len; } // compute and return volume double volume() { return width * length * depth; } }
  • 42.
    42 class BoxWeight extendsBox { double weight; // constructor for BoxWeight with 4 arguments BoxWeight(double w, double l, double d, double m) { width = w; length = l; depth = d; weight = m; } }
  • 43.
    43 class DemoBoxWeight { publicstatic void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } }
  • 44.
    Use of super-Thesuper keyword in Java is a reference variable that is used to refer to parent class when we’re working with objects. 44
  • 45.
    45 class Box { privatedouble width; private double length; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; length = ob.length; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double l, double d) { width = w; length = l; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate length = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = length = depth = len; } // compute and return volume double volume() { return width * length * depth; } }
  • 46.
    46 // BoxWeight nowfully implements all constructors. class BoxWeight extends Box { double weight; // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } // constructor when all parameters are specified BoxWeight(double w, double l, double d, double m) { super(w, l, d); // call superclass 3 argument constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } }
  • 47.
    47 class DemoSuper { publicstatic void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); BoxWeight mybox3 = new BoxWeight(); // default BoxWeight mycube = new BoxWeight(3, 2); BoxWeight myclone = new BoxWeight(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + System.out.println(); vol = mybox3.volume(); System.out.println("Volume of mybox3 is " + vol); System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println(); vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } }
  • 48.
    Order of constructorcalling in Inheritance 48
  • 49.
    49 // Create asuper 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 CallingCons { public static void main(String args[]) { C c = new C();
  • 50.
    50 O/P: Inside A’s Constructor InsideB’s Constructor Inside C’s Constructor
  • 51.
  • 52.
    52 // Method overriding. classA { 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); 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 } }
  • 53.
    Another Style class Bextends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } } 53
  • 54.
  • 55.
    Abstract Classes • Classcontaining one or more function as abstract is known as abstract class and therefore its declaration should be preceded with the keyword abstract. • An Abstract class is a conceptual class. • An Abstract class cannot be instantiated – objects cannot be created. • A class declared abstract, even with no abstract methods can not be instantiated. • A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them. • A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated. 55
  • 56.
    Abstract Class Syntax abstractclass ClassName { ... … abstract Type MethodName1(); … … Type Method2() { // method body } } • When a class contains one or more abstract methods, it should be declared as abstract class. • The abstract methods of an abstract class must be defined in its subclass. • We cannot declare abstract constructors or abstract static methods. 56
  • 57.
    57 For eg: abstract classFigure { double dim1; double dim2; Figure(double a, double b) { dim1 = a; dim2 = b; } // area is now an an abstract method abstract double area(); }
  • 58.
    58 class Rectangle extendsFigure { Rectangle(double a, double b) { super(a, b); } // override area for rectangle double area() { System.out.println("Inside Area for Rectangle."); return dim1 * dim2; } } class Triangle extends Figure { Triangle(double a, double b) { super(a, b); } // override area for right triangle double area() { System.out.println("Inside Area for Triangle."); return dim1 * dim2 / 2; } }
  • 59.
    59 class AbstractAreas { publicstatic void main(String args[]) { // Figure f = new Figure(10, 10); is illegal now as it cannot be instantiated Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); System.out.println("Area is " + r.area()); System.out.println("Area is " + t.area()); } }
  • 60.
    Final Members: Away for Preventing Overriding of Members in Subclasses • All methods and variables can be overridden by default in subclasses. • This can be prevented by declaring them as final using the keyword “final” as a modifier. For example: • final int marks = 100; • final void display(); • This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered. 60
  • 61.
    61 FINAL METHOD class A{ final void meth() { System.out.println("This is a final method."); } } class B extends A { void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } } FINAL CLASS final class A { // ... } // The following class is illegal. class B extends A { // ERROR! Can't subclass A // ... }
  • 62.
    Interfaces 62 Design Abstraction anda way for achieving Multiple Inheritance
  • 63.
    Interfaces • Interface isa conceptual entity similar to a Abstract class. • Can contain only constants (final fields) and abstract method. (no implementation) - Different from Abstract classes. • When number of classes share a common interface each class should implement the interface. 63
  • 64.
    Features of anInterface • An interface is basically a kind of class—it contains methods and final fields. • Therefore, it is the responsibility of the class that implements an interface to supply the code for methods. • A class can implement any number of interfaces, but cannot extend more than one class at a time. • Therefore, interfaces are considered as an informal way of realising multiple inheritance in Java. 64
  • 65.
    Interface - Example 65 speak() PoliticianPriest <<Interface>> Speaker speak() speak() Lecturer speak()
  • 66.
    Interfaces Definition • Syntax(appears like abstract class): • Example: 66 interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } interface Speaker { public void speak( ); }
  • 67.
    Implementing Interfaces • Interfacesare used like super-classes who properties are inherited by classes. This is achieved by creating a class that implements the given interface as follows: 67 class ClassName implements InterfaceName [, InterfaceName2, …] { // Body of Class }
  • 68.
    Implementing Interfaces Example 68 class Politicianimplements Speaker { public void speak(){ System.out.println(“Talk politics”); } } class Priest implements Speaker { public void speak(){ System.out.println(“Religious Talks”); } } class Lecturer implements Speaker { public void speak(){ System.out.println(“Talks Object Oriented Design and Programming!”); } }
  • 69.
    Extending Interfaces • Likeclasses, interfaces can also be extended. The new sub-interface will inherit all the members of the superinterface in the manner similar to classes. This is achieved by using the keyword extends as follows: 69 interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }
  • 70.
    Inheritance and Interface Implementation •A general form of interface implementation: • This shows a class can extended another class while implementing one or more interfaces. It appears like a multiple inheritance (if we consider interfaces as special kind of classes with certain restrictions or special features). 70 class ClassName extends SuperClass implements InterfaceName [, InterfaceName2, …] { // Body of Class }
  • 71.
    71 /* An exampleJava Program to demontrate the working of an Interface*/ interface Shape { float PI=3.14f; float computeArea(); } class Circle implements Shape { float radius; Circle (float r) { radius=r; } public float computeArea() { return PI*radius*radius; } } class IntfTest { public static void main(String args[]) { Circle c1=new Circle(7.0f); float ar=0.0f; ar=c1.computeArea(); System.out.println("Area is = "+ar); } }
  • 72.
    72 Java 8 DefaultMethods Interfaces in Java always contained method declaration not their definitions (method body). There was no way of defining method body / definition in interfaces. This is because historically Java didn’t allow multiple inheritance of classes. It allowed multiple inheritance of interfaces as interface were nothing but method declaration. This solves the problem of ambiguity in multiple inheritance. Since Java 8 has a new feature called Default Methods. It is now possible to add method bodies into interfaces!
  • 73.
    73 public interface Math intadd(int a, int b); default int multiply(int a, int b) { return a * b; } } n above Math interface we added a method multiply with actual method body.
  • 74.
    74 Why we needDefault Methods? or Why would one want to add methods into Interfaces? We’ll it is because interfaces are too tightly coupled with their implementation classes. i.e. it is not possible to add a method in interface without breaking the implementer class. Once you add a method in interface, all its implemented classes must declare method body of this new method.
  • 75.
    75 What about MultipleInheritance? Adding method definitions in interfaces can add ambiguity in multiple inheritance. isn’t it? Well, it does. However Java 8 handle this issue at Compile type. Consider below example: interface Person { default void sayHello() { System.out.println("Hello"); } } interface Male { default void sayHello() { System.out.println("Hi"); } } class Sam implements Person, Male { }
  • 76.
    76 In this examplewe have same defender method sayHello in both interfaces Person and Male. Class Sam implements these interfaces. So which version of sayHello will be inherited? We’ll if you try to compile this code in Java 8, it will give following error. class Sam inherits unrelated defaults for sayHello() from types Person and Male class Sam implements Person, Male { ^ 1 error So that solves multiple inheritance problem. You cannot implement multiple interfaces having same signature of Java 8 default methods (without overriding explicitly in child class).
  • 77.
    77 We can solvethe above problem by overriding sayHello method in class Sam. interface Person { default void sayHello() { System.out.println("Hello"); } } interface Male { default void sayHello() { System.out.println("Hi"); } } class Sam implements Person, Male { void sayHello() //override the sayHello to resolve ambiguity { } }
  • 78.
    78 It is alsopossible to explicitly call method from child class to parent interface. Consider in above example you want to call sayHello method from Male interface when Sam.sayHello is called. You can use super keyword to explicitly call the appropriate method. class Sam implements Person, Male { //override the sayHello to resolve ambiguity void sayHello() { Male.super.sayHello(); } }
  • 79.
    Package a Collection of Classes$ Interfaces bundled together Ms Gargi Mukherjee 79
  • 80.
    80 Introduction • The mainfeature of OOP is its ability to support the reuse of code: • Extending the classes (via inheritance) • Extending interfaces • The features in basic form limited to reusing the classes within a program. • What if we need to use classes from other programs without physically copying them into the program under development ? • In Java, this is achieved by using what is known as “packages”, a concept similar to “class libraries” in other languages.
  • 81.
    Packages • Packages areJava’s way of grouping a number of related classes and/or interfaces together into a single unit. That means, packages act as “containers” for classes. • The benefits of organising classes into packages are: • The classes contained in the packages of other programs/ applications can be reused. • In packages classes can be unique compared with classes in other packages. That is two classes in two different packages can have the same name. If there is a naming clash, then classes can be accessed with their fully qualified name. • Classes in packages can be hidden if we don’t want other packages to access them. • Packages also provide a way for separating “design” from coding. 81
  • 82.
  • 83.
    Java Foundation Packages •Java provides a large number of classes groped into different packages based on their functionality. • The six foundation Java packages are: • java.lang • Contains classes for primitive types, strings, math functions, threads, and exception • java.util • Contains classes such as Random, Vector,Collections, hash tables, date etc. • java.io • Stream classes for I/O • java.awt • Classes for implementing GUI – windows, buttons, menus etc. • java.net • Classes for networking • java.applet • Classes for creating and implementing applets 83
  • 84.
    Using System Packages •The packages are organised in a hierarchical structure. For example, a package named “java” contains the package “awt”, which in turn contains various classes required for implementing GUI (graphical user interface). 84 Graphics Font java Image … awt lang “java” Package containing “lang”, “awt”,.. packages; Can also contain classes. awt Package containing classes Classes containing methods
  • 85.
    Accessing Classes fromPackages • There are two ways of accessing the classes stored in packages: • Using fully qualified class name • java.lang.Math.sqrt(x); • Import package and use class name directly. • import java.lang.Math • Math.sqrt(x); • Selected or all classes in packages can be imported: • Implicit in all programs: import java.lang.*; • package statement(s) must appear first 85 import package.class; import package.*;
  • 86.
    Creating Packages • Javasupports a keyword called “package” for creating user- defined packages. The package statement must be the first statement in a Java source file (except comments and white spaces) followed by one or more classes. • Package name is “myPackage” and classes are considred as part of this package; The code is saved in a file called “ClassA.java” and located in a directory called “myPackage”. 86 package myPackage; public class ClassA { // class body } class ClassB { // class body }
  • 87.
    Creating Sub Packages •Classes in one ore more source files can be part of the same packages. • As packages in Java are organised hierarchically, sub-packages can be created as follows: • package myPackage.Math • package myPackage.secondPakage.thirdPackage • Store “thirdPackage” in a subdirectory named “myPackagesecondPackage”. Store “secondPackage” and “Math” class in a subdirectory “myPackage”. 87
  • 88.
    Accessing a Package •As indicated earlier, classes in packages can be accessed using a fully qualified name or using a short-cut as long as we import a corresponding package. • The general form of importing package is: • import package1[.package2][…].classname • Example: • import myPackage.ClassA; • import myPackage.secondPackage • All classes/interfaces from higher-level package can be imported as follows: • import myPackage.*;but it does’nt mean we have imported all other sub packages of mypackage. 88
  • 89.
    Using a Package •Let us store the code listing below in a file named “ClassA.java” within subdirectory named “myPackage” within the current directory (say “bin”). 89 package myPackage; public class ClassA { // class body public void display() { System.out.println("Hello, I am ClassA"); } } class ClassB { // class body }
  • 90.
    Using a Package •Within the current directory (“bin”) store the following code in a file named “ClassX.java” 90 import myPackage.ClassA; public class ClassX { public static void main(String args[]) { ClassA objA = new ClassA(); objA.display(); } }
  • 91.
    Compiling and Running •When ClassX.java is compiled, the compiler compiles it and places .class file in current directly. If .class of ClassA in subdirectory “myPackage” is not found, it compiles ClassA also. • Note: It does not include code of ClassA into ClassX • When the program ClassX is run, java loader looks for ClassA.class file in a package called “myPackage” and loads it. 91
  • 92.
  • 93.
    Using a Package •Let us store the code listing below in a file named “ClassA.java” within subdirectory named “secondPackage” within the current directory (say “abc”). 93 package secondPackage; public class ClassC { // class body public void display() { System.out.println("Hello, I am ClassC"); } }
  • 94.
    Using a Package •Within the current directory (“abc”) store the following code in a file named “ClassX.java” 94 import myPackage.ClassA; import secondPackage.ClassC; public class ClassY { public static void main(String args[]) { ClassA objA = new ClassA(); ClassC objC = new ClassC(); objA.display(); objC.display(); } }
  • 95.
    Output java ClassY Hello, Iam ClassA Hello, I am ClassC 95
  • 96.
    Protection and Packages •All classes (or interfaces) accessible to all others in the same package. • Class declared public in one package is accessible within another. Non-public class is not • Members of a class are accessible from a difference class, as long as they are not private • protected members of a class in a package are accessible to subclasses in a different class 96
  • 97.
    Visibility - Revisited •Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible. • Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. • Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class. 97
  • 98.
    Visibility Modifiers 98 Accessible to:public protected Package (default) private Same Class Yes Yes Yes Yes Class in package Yes Yes Yes No Subclass in different package Yes Yes No No Non-subclass different package Yes No No No
  • 99.
    Access Modifiers inJava • There are two types of modifiers in Java: access modifiers and non-access modifiers. • The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. • There are four types of Java access modifiers: 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. 4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
  • 100.
    Private The private accessmodifier is accessible only within the class. class A{ private int data=40; private void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data);//Compile Time Error obj.msg();//Compile Time Error } }
  • 101.
    Default • If youdon't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public. //save by A.java package pack; class A{ void msg(){System.out.println("Hello");} }
  • 102.
    //save by B.java packagemypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A();//Compile Time Error obj.msg();//Compile Time Error } }
  • 103.
    • The protectedaccess modifier is accessible within package and outside the package but through inheritance only. • The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. • It provides more accessibility than the default modifer. package pack; public class A{ protected void msg(){System.out.println("Hello");} }
  • 104.
    //save by B.java packagemypack; import pack.*; class B extends A{ public static void main(String args[]){ B obj = new B(); obj.msg(); } }
  • 105.
    Public • The publicaccess modifier is accessible everywhere. It has the widest scope among all other modifiers. package pack; public class A{ public void msg(){System.out.println("Hello");} } package mypack; import pack.*; class B{ public static void main(String args[]){ A obj = new A(); obj.msg(); } }
  • 106.
    Adding a Classto a Package • Consider an existing package that contains a class called “Teacher”: • This class is stored in “Teacher.java” file within a directory called “pack1”. • How do we a new public class called “Student” to this package. 10 6 package pack1; public class Teacher { // class body }
  • 107.
    Adding a Classto a Package • Define the public class “Student” and place the package statement before the class definition as follows: • Store this in “Student.java” file under the directory “pack1”. • When the “Student.java” file is compiled, the class file will be created and stored in the directory “pack1”. Now, the package “pack1” will contain both the classes “Teacher” and “Student”. 10 7 package pack1; public class Student { // class body } class Teacher package pack1; class Student
  • 108.
    Packages and NameClashing • When packages are developed by different organizations, it is possible that multiple packages will have classes with the same name, leading to name classing. • We can import and use these packages like: • import pack1.*; • import pack2.*; • Student student1; // Generates compilation error 10 8 class Teacher package pack1; class Student class Student package pack2; class Courses
  • 109.
    Handling Name Clashing •In Java, name classing is resolved by accessing classes with the same name in multiple packages by their fully qualified name. • Example: import pack1.*; import pack2.*; pack1.Student student1; pack2.Student student2; Teacher teacher1; Courses course1; 10 9
  • 110.
    Extending a Classfrom Package • A new class called “Professor” can be created by extending the “Teacher” class defined the package “pack1” as follows: 11 0 import pack1.Teacher; public class Professor extends Teacher { // body of Professor class // It is able to inherit public and protected members, // but not private or default members of Teacher class. }
  • 111.
    Summary • Packages allowgrouping of related classes into a single united. • Packages are organised in hierarchical structure. • Packages handle name classing issues. • Packages can be accessed or inherited without actual copy of code to each program. 11 1
  • 112.
    Exception Handling injava By Gargi Mukherjee
  • 113.
    Exceptions Exception are suchanomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language.
  • 114.
    Java Exception isan object that describes an exceptional condition that has occurred in a piece of code. When exception takes place, an object representing that condition is created and thrown in the method that caused the error. Then this exception is caught and processed.
  • 115.
    Advantages of exceptionhandling 1. Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. 2. With the help of this mechanism the working code and the error-handling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. 3. Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain .
  • 116.
  • 117.
    Exception class isused for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. Error class defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. Note: This chapter will not be dealing with exceptions of type Error, because these are typically created in response to catastrophic failures that cannot usually be handled by your program.
  • 118.
    Java exception handlingis managed via five keywords: try, catch, throw, throws, and finally. Program statements that we want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Our code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block.
  • 119.
    This is thegeneral form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } finally { // block of code to be executed before try block ends } Here, ExceptionType is the type of exception that has occurred.
  • 120.
    Uncaught Exceptions Before youlearn how to handle exceptions in your program, it is useful to see what happens when you don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error. class Exc { public static void main(String args[]) { int d = 0; int a = 42 / d; } }
  • 121.
    When the Javarun-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. Here is the output generated when this example is executed. java.lang.ArithmeticException: / by zero at Exc.main(Exc0.java:4)
  • 122.
    Using try andcatch Although the default exception handler provided by the Java run-time system is useful for debugging, we will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating.
  • 123.
    To guard againstand handle a run- time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.
  • 124.
    class Exc2 { public staticvoid main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement.
  • 125.
    Catch is nota function Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
  • 126.
    Multiple Catch Clauses Insome cases, more than one exception could be raised by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
  • 127.
    class MultiCatch { publicstatic void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 128.
    This program willcause a division-by-zero exception if it is started with no commandline parameters, since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42]. Here is the output generated by running it both ways: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.
  • 129.
    Java’s Built-in Exceptions UncheckedException Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size.
  • 130.
  • 131.
    Throw- Java throwkeyword is used to throw an exception explicitly. We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. A snippet below public class TestThrow2 { //function to check if person is eligible to vote or not public static void method() throws FileNotFoundExcept ion { FileReader file = new FileReader("C:UsersAnurati Desktopabc.txt"); BufferedReader fileInput = new BufferedReader(file); throw new FileNotFoundException(); }
  • 132.
    public class TestThrow3 { publicstatic void main(String args[]) { try { // throw an object of user defined exception throw new UserDefinedException("This is user-defined exception"); } catch (UserDefinedException ude) { System.out.println("Caught the exception"); // Print the message from MyException object System.out.println(ude.getMessage()); }
  • 133.
    throws If a methodis capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw.
  • 134.
    Following is anexample of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile. // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } }
  • 135.
    To make thisexample compile, you need to make two changes. First, you need to declare that throwOne( ) throws IllegalAccessException. Second, main( ) must definea try/catch statement that catches this exception. The corrected example is shown here: // This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo
  • 136.
  • 137.
    • 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..."); • } • }
  • 138.
  • 139.
    Java Nested tryblock • In Java, using a try block inside another try block is permitted. It is called as nested try block. Every statement that we enter a statement in try block, context of that exception is pushed onto the stack. • For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
  • 140.
    • /main tryblock • try • { • statement 1; • statement 2; • //try catch block within another try block • try • { • statement 3; • statement 4; • //try catch block within nested try block • try • { • statement 5; • statement 6; • } • catch(Exception e2) • { • //exception message • } • • } • catch(Exception e1) • { • //exception message • } • } • //catch block of parent (outer) try block • catch(Exception e3) • { • //exception message • } • ....
  • 141.
    finally When exceptions arethrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. Depending upon how themethod is coded, it is even possible for an exception to cause the method to return prematurely. This could be a problem in some methods. For example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception- handling mechanism. The finally keyword is designed to address this contingency. finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional.
  • 142.
    class FinallyDemo { //Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } // Return from within a try block. static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } } // Execute a try block normally.
  • 143.
    static void procC(){ try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); } }
  • 144.
    Here is theoutput generated by the preceding program: inside procA procA’s finally Exception caught inside procB procB’s finally inside procC procC’s finally
  • 145.
    // This programcreates a custom exception type. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } }
  • 146.
    class ExceptionDemo { staticvoid compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
  • 147.
    OUTPUT Called compute(1) Normal exit Calledcompute(20) Caught MyException[20]