INHERITANCE INTERFACE &
PACKAGE
Marks-12
Inheritance in Java
Mechanism of deriving new class from old class.
Supports “Reusability”
The old class is known as-
Base Class / Super class / Parent Class
The new class is known as-
Derived class/ Sub Class / Child class
Sub class can add its own fields and methods.
Properties of super class are accessible to the
sub class
Inheritance in Java
Types:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
Multiple Inheritance is supported by Java using
Interface .
Inheritance in Java
General Syntax:
access-specifier class Subclassname extends
Supeclassname implements
Interfacename1,Interfacename2,…,InterfacenameN
{
//body of the sub class
}
Inheritance In Java
Single inheritance -
When a class extends another one class
only then we call it a single inheritance. A
The flow diagram shows that class B
extends only one class which is A.
Here A is a parent class of B and B
would be a child class of A. B
Inheritance In Java
Single inheritance -
Syntax:
class A
{
A
-------
-------
}
class B extends A B
{
-------
-------
}
Single Inheritance example program in Java
class A
{
public void methodA()
{
System.out.println(“Super class method");
}
}
class B extends A
{
public void methodB()
{
System.out.println(“Sub class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling sub class method
}
}
“Multiple Inheritance”
“Multiple Inheritance” refers to the concept of
one class extending (Or inherits) more than one
base class.
In Java, multiple inheritance is implemented using
interface concept.
A B
C
Multilevel Inheritance
Multilevel inheritance refers to a mechanism
where one can inherit from a derived class,
thereby making this derived class as base class for
the new class.
In flow diagram, C is subclass or child class of B and
B is a child class of A. A
B
C
Inheritance In Java
Multilevel inheritance -
Syntax:
class A
{
-------
A
-------
}
class B extends A
B
{
------- C
-------
}
class C extends B
{
-------
Multilevel Inheritance example program in Java
class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling own method
}
Hierarchical Inheritance
In such kind of inheritance one class is inherited
by many sub classes.
In below example class B,C and D inherits the
same class A.
A is parent class (or base class) of B,C & D.
B C D
Inheritance In Java
Hierarchical inheritance -
Syntax:
class A
{
-------
A
-------
}
class B extends A
{ B C
-------
-------
}
class C extends A
{
-------
Hierarchical Inheritance example program in Java
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class MyClass
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
obj1.methodA(); //calls parent method
obj1.methodB(); //calls own method
obj2.methodA(); //calls parent method
obj2.methodC(); //calls own method
}
}
Uses of Super keyword
Used by subclass to refer or to access superclass
members
It is a reference variable that is used to refer parent
class
The keyword “super” is always used with the
concept of Inheritance.
Three uses of super Keyword :
Accessing instance variables of super class
Accessing instance methods of super class
Calling super class constructor
Uses of Super keyword
1) Accessing instance variables of super class
Used to access instance variable of super class in subclass
Also used when superclass and subclass has the same name for instance
variable
Syntax:
super.variablename;
2) Accessing instance methods of super class
Used to access instance methods of super class in subclass
Also used in the case of method overriding
Syntax:
super.methodname(para-list);
3) Calling super class constructor
Used to call super class constructor within a subclass constructor.
The call to super must appear as first statement.
Syntax:
class Primary {
int cal; //declaration1
Primary(int a)
{
cal = a;
}
void show()
{
System.out.println("Super class cal : "+cal);
}
}
class Secondary extends Primary
{
int cal; //declaration2
Secondary(int x,int y)
{
super(x); //use of super to call superclass constructor
cal = y;
}
void show()
{
super. show (); //use of super to access super class instance method
System.out.println ("Sub class cal: "+cal);
}
}
class SuperUse
{
public static void main(String args[])
{
Secondary s = new Secondary (15,22);
s.show();
}
}
Method Overloading
Defining two or more methods within the same
class that are having the same name, but their
parameter declarations are different.
the methods are said to be overloaded, and the
process is referred to as method overloading.
implementation of polymorphism
type and/or number of arguments are used to
determine which version of the overloaded method to
actually call
Program on Method Overloading
class Area
{
int area(int side) //area of a square
{
return(side * side);
}
float area(float radius) //area of circle
{
return(3.14f * radius * radius);
}
int area(int len, int wid) //area of rectangle
{
return(len * wid);
}
}
Program on Method Overloading (Continued)
class Shape
{
public static void main(String args[])
{
Area s = new Area();
int x=s.area(10);
System.out.println ("Area of square : "+x);
int y=s.area(10,20);
System.out.println ("Area of rect: "+y);
float z = s.area(5.5f);
System.out.println ("Area of circle : "+z);
}
}
Output:
Area of square : 100
Area of rect: 200
Overriding Methods
Method overriding means have same signature but
with different implementation.
Signature includes method name, arguments and
return type
If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding.
Forms basis for run-time polymorphism.
Advantage of Java Method Overriding
provide subclass specific implementation of a method that is
Overriding Methods
Rules for Method Overriding
method must have same name as in the parent class
method must have same parameter/argument as in the
parent class.
must be IS-A relationship (inheritance)
Instance methods can be overridden only if they are
inherited by the subclass.
If a method cannot be inherited, then it cannot be
overridden.
A method declared final cannot be overridden.
A method declared static cannot be overridden.
Constructors cannot be overridden.
Program on Overriding
class Vehicle
{
void show ()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void show()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike obj = new Bike();
obj.show(); //calls subclass show()
}
}
Sr.
No Method Overloading Method Overriding
A relationship between methods is A relationship between methods is
1 available in the same class. available in the super class and its sub
class
Method signature should not be same. Method signature should be same.
2 Only name of the method should be
same.
3 It is a compile time polymorphism. It is a run time polymorphism.
Method can have any return type. Method return type must be same as
4 super class method
5 Method can have any access level. Method must have same access level
No need of inheritance in Method It always requires inheritance in Method
6 Overloading. It is performed within the Overriding.
same class
Sr.
No Method Overloading Method Overriding
For Example: For Example:
class Add class A // Super Class
{
{ void display(int num)
int sum(int a, int b) {
{ System.out.println(“num in super class=”+num);
return a + b; }
}
} class B //Sub Class
7 int sum(int a) {
{ void display(int num)
{
return a + 10; System.out.println(“num in subclass=”+num);
} }
} }
Dynamic Method Dispatch
Java implements run-time polymorphism using
Dynamic method dispatch.
Dynamic method dispatch is the mechanism by which
a call to an overridden method is resolved at run time.
When an overridden method is called through a
super class reference, Java determines which version
of that method to execute based upon the type of
the object being referred to at the time the call
occurs. Thus, this determination is made at run time.
Dynamic Method Dispatch
When Parent class reference variable refers to
Child class object, it is known as Upcasting.
Program on Dynamic Method Dispatch
class A class Dynamic
{ {
void display() public static void main(String args[])
{ {
System.out.println (“A's A a = new A (); // object of type A
display"); B b = new B (); // object of type
} B
}
class B extends A A r; // obtain a reference of type A
{ a.display (); // calls A's version of
void display() // override display
display()
{ r = b; // r refers to a B object
System.out.println (“B‘s r.display (); // calls B's version of
display "); display
} }
Uses of Final keyword
The keyword final has three uses:
1. It can be used to create the constant.
2. It can be used to Prevent method Overriding.
3. it can be used to Prevent Inheritance.
The last two uses of final apply to inheritance.
Final Variable
Makes the constant
When a variable is declared as final, then value of
the final variable never be changed.
declare variable as final using final keyword.
final datatype variablename=value;
Example:
final int size=20;
Program Final variable
class A
{
final int size=20;
void display() size is declared as final, its
{ value cannot be changed.
size=size+5; //ERROR If you attempt to do so, a
System.out.println (“size=“+size); compile-time error will
}
result.
public static void main(String args[])
{
A obj=new A();
obj.display();
}
}
Final Methods
Prevents method overriding
To prevent the subclasses from overriding the
methods of the superclass, declare them as final
using final keyword.
final returntype methodname(parameter list)
{
//method body
}
Defining method final ensures that functionality of
defined method will not be altered.
Program Final Methods (Preventing Overriding)
class A
{
final void meth()
{
System.out.println ("This is a final method.");
}
}
class B extends A
{ meth( ) is declared as
void meth() // ERROR! Can't override. final, it cannot be
{ overridden in B. If you
System.out.println ("Illegal!");
attempt to do so, a
}
compile-time error will
}
result.
Final Classes
Prevents Inheritance
A class that can not be sub-classed is called final class.
To make the class as final , class declaration is preceded by final
keyword.
Declaring a class as final implicitly declares all of its methods as final
too
final class A
{
…
}
class B extends A //ERROR
{
…
Program Final class (Preventing Inheritance)
final class A
{
void meth()
{
System.out.println ("This is a final method from final class A.");
}
}
class B extends A // ERROR! Can't be subclass of A
{
Class A is declared as final, so it
void disp()
cannot be inherited. Means we
{
System.out.println (“Diaplay"); cannot create subclass of class A. If
} you attempt to do so, a compile-
} time error will result.
Abstract Methods and Classes
A class declared as abstract is known as abstract class.
It needs to be extended and its method implemented.
Abstract class can include concrete as well as abstract
methods
It cannot be instantiated. Objects cannot be created.
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
We cannot declare abstract constructors or abstract
static methods.
Syntax to declare the abstract class
abstract class ClassName
{
abstract Type MethodName1( );
…
Type Method2()
{
// method body
}
}
Abstract Methods and Classes
Abstract Method
• A method that is declared as abstract and does not
have implementation is known as abstract method.
• Static, final and private methods cannot be abstract.
since they cannot be overridden
• Final class cannot contain abstract methods.
Syntax to define the abstract method
abstract return_type method_name();
//no braces{}
Example
abstract class Bike
{
abstract void display( );
}
class Honda extends Bike
{
void display()
{ System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda();
obj.display();
}
Static members
to define a members that is common to all the objects
and accessed without using a particular object.
these members belongs to the class
Such members are created by preceding them with the
keyword static
The static members are initialized once.
both methods and variables can be declared as static.
Static members
Syntax to declare the static variables
static datatype variablename;
static datatype variablename=value;
Syntax to create static method:
static returntype methodname(parameter-list)
{
//body of static method
}
Static members
For example:
static int cal;
static float min = 1;
static void display(int x)
{
System.out.println(x);
}
To access static members, class name is used.
classname.staticmember;
Static members
Static Methods static have several restrictions:
1. They can only directly call other static
methods.
2. They can only directly access static data. It can
not access non-static data
3. They cannot refer to this or super in any way.
Why no multiple inheritance through class?
Consider classes A,B, and C.
C is subclass of class A and B
If class A and B defines the same method as display()
Then Class C inherits method display() twice i.e from class A as
well class B
When subclass object calls display() method, there is ambiguity
that which method to call.
Why no multiple inheritance through class?
To avoid such situations, Java does not allow us to
extend more than one class.
In java multiple inheritance is achieved through
concept known as “Interface”
Interface
Interface is a conceptual entity similar to a Abstract
class.
Interface looks like a class but it is not a class
Can contain only constants (final variables) and
abstract method (no implementation)
The class that implements interface must implement all
the methods of that interface.
variables declared in an interface are public, static & final
by default.
Interface members are public.
Interface can not instantiated. Objects can not be
created.
Interface
A class can implement any number of interfaces, but
cannot extend more than one class at a time.
Interfaces cannot be final because interface must be
implemented to define its abstract method.
Syntax:
interface InterfaceName
{
public static final variable1=value;
……
public void method1();
public void method2();
….
}
Interface
Example: Example:
1) interface Speaker 3) interface Circle
{ {
public void speak( ); float pi=3.14f;
} }
2)interface Sports
{
float marks=5.4f;
public void show ( );
}
Relationship between classes and interfaces
51 As shown in the figure given below, a class extends
another class.
An interface extends another interface but a class
implements an interface
52
The java compiler adds public and abstract keywords
before the interface method and public, static and final
keywords before data members.
Implementing Interfaces
53
Interfaces are used like super-classes who's
properties are inherited by classes.
A class uses the implements keyword to implement
an interface.
A class can extend only one class, but implement many
interfaces.
syntax
class ClassName implements Interface1,Interface2, …, InterfaceN
{
// Body of Class
}
Implementing Interfaces Example
interface Speaker
54
{
void speak( );
}
class Lecturer implements Speaker
{
public void speak()
{
System.out.println(“Speaks about Java
Programming!”);
}
public static void main(String args[])
{
Lecturer lect=new Lecturer();
lect.speak();
}
}
Extending Interfaces
An interface can extend another interface
55
The extends keyword is used
Child interface inherits the methods of the parent interface.
Interface can extend multiple interface.
syntax
interface InterfaceName extends interface1, interface2, …, interfaceN
{
//interface body
}
interface Interface1 Extending Interfaces Example
{
void f1();
56
}
interface Interface2 extends Interface1
{
void f2();
}
class Demo implements Interface2
{
public void f1()
{
System.out.println("Contents of Method f1() in Interface1");
}
public void f2()
{
System.out.println("Contents of Method f2() in Interface2");
}
public void f3()
{
System.out.println("Contents of Method f3() of Class Demo");
}
}
57 class ExtendingInterface
{
public static void main(String[] args)
{
Demo d=new Demo();
d.f1();
d.f2();
d.f3();
}
}
Nested Interfaces
58
An interface i.e. declared within another interface or class is
known as nested interface.
used to group related interfaces
Can't be accessed directly.
Nested interface must be referred by the outer interface or
class
Nested interface must be public if it is declared inside the
interface but it can have any access modifier if declared within
the class.
Nested interfaces are declared static implicitely.
Syntax of nested interface which is declared within the interface
interface interface_name
{
...
interface nested_interface_name
{
...
}
}
Syntax of nested interface which is declared within the class
class class_name
{
...
interface nested_interface_name
{
...
}
interface Test
{
interface Message
{
void msg();
}
}
Class NestDemo implements Test.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
NestDemo nd=new NestDemo ();
nd.msg();
}
Interfaces References
61
A reference variable can be declared as a class type or
an interface type.
Interface reference variable can reference any object
of any class that implements .the interface.
(upcasting).
Used to achives runtime polymorphism
interface Test
{
interface Message
{
void msg();
}
}
Class NestDemo implements Test.Message
{
public void msg()
{
System.out.println("Hello nested interface");
}
public static void main(String args[])
{
Test.Message nd=new NestDemo ();
nd.msg();
}
Multiple Inheritance
63
A class can inherit properties of more than one parent class.
Java does not allows to extend more than one class.
Java doesn’t provide support for multiple inheritance
in classes.
For eg:
class C extends A,B
{
------
------
}
this code is not valid in java.
Multiple Inheritance in Java
there can be one class and one interface at parent
level to achieve multiple inheritance
Interface contains final variables and abstract
method.
Interfaces can be implemented by a derived class.
Syntax
class ClassName extends Superclass implements
Interface1,Interface2, …, InterfaceN
{
// Body of Class
}
Write a program to implement foll. inheritance
Packages in Java
A java package is a group of similar types of
classes, interfaces and sub-packages.
package are container for a classes
The package is both naming and visibility
controlled mechanism.
Package can be categorized in two form,
1. built-in package (Java API packages)
2. user-defined package.
Advantages of using package
Better Organization : Packages are used to
categorize the classes and interfaces so that they
can be easily maintained.
provides access protection.
Removes naming collision: define two classes
with the same name in different packages
Reusability
Java API packages /Built-in packages
The java API provides a no. of classes grouped
into different packages according to their
functionality.
Java API packages /Built-in packages
java.lang Contains language support classes ( for e.g classes
which defines primitive data types, math
operations, etc.) . This package is automatically
imported.
java.io Contains classes for supporting input / output
operations.
java.util Contains utility classes which implement data
structures like Linked List, Hash Table, Dictionary,
etc and support for Date / Time operations.
java.applet Contains classes for creating Applets.
java.awt Contains classes for implementing the
components of graphical user interface ( like
buttons, menus, etc. ).
java.net Contains classes for supporting networking
operations.
Naming Conventions:-
Packages in java can be named using standard
java naming rules.
E.g.
1) java.awt.Color;
awt- package name, Color-class name
2) double x= java.lang.Math.sqrt(a);
lang- package name, math- class name, sqrt-
method name
Creating User defined packages
Creation of packages includes following steps.
1) Declare a package at the beginning of the file using the
following form.
package package_name
e.g.
package pkg; - name of package
package is the java keyword with the name of package.
This must be the first statement in java source file.
Creating packages/ Defining Packages:-
2) Define a class which is to be put in the package and declare
it public like following way.
package pkg;
public class Demo
{
//Body of class;
}
In above example, “pkg” is the package name. The class
“Demo” is now considered as a part of this package.
3) Create a sub-directory under the directory where the main
source files are stored.
Creating packages/ Defining Packages:-
4) Store the listing of, as classname.java file is the sub-
directory created.
e.g. from the above package we can write “Demo.java”
5) Compile the source file. This creates .class file is the sub-
directory.
Program on creating packages/user defined
packages
Package file stored in package directory Source file stored in one directory
above the package directory
package package1;
import package1.Box;
public class Box class Volume
{ {
int l= 5; public static void main(String args[])
int b = 7; {
int h = 8; Box b=new Box();
public void display()
b.display();
}
{
}
System.out.println("Volume is:"+(l*b*h));
}
}
Adding class to a package
Consider the we have package ‘P’ and suppose class B is to be
added to following package.
package P;
{
Public class B;
{
//body of B;
}
}
The package ‘P’ contains one public class named as ‘A’
For adding class B to this package follows given steps
Adding class to a package
For adding class X to this package follows given steps
1) Define the class & make it as public.
2) Place package statement Package P; Before the class definition as
follows
Package P;
Public class B
{
// Body of B
}
3) Store this as B.java file under directory P;
4) Compile B.java file. This will create B.class file and place it in
the directory P.
Now, the package “P” contains both the classes A and B. So to
import both classes use import P.*;
Static import
Eliminates the need of qualifying a static member with the
class name.
The static import declaration is similar to that of import.
We can use static import statement to import static members
from classes and use them without qualifying class name.
import static package-name.sub-package-name.
class-name.Staticmember-name;
Or
import static package-name.subpackage-name. class-
name.*;
Example of Static import
import static java.lang.Math.*;
public class MathOp
{
public void circle(double r)
{
double area=PI*r*r;
System.out.println(“The area of Circle is :”+area);
}
public static void main(String args[])
{
mathop obj=new mathop();
obj.circle(2.3);
}
}