UNIT III
INHERITANCE AND POLYMORPHISM
CONTENTS
Types of Inheritance-Method Overriding - super keyword - Dynamic Method Dispatch (Runtime
Polymorphism) - Abstract Classes and Methods Interfaces and Multiple Inheritance in Java -
Java Packages -and Access Modifiers
1. Types of Inheritance in Java
Java supports the following types of inheritance:
Type Description Supported in Java
Single One class inherits from another ✅
Multilevel A class inherits from a derived class ✅
Hierarchical Multiple classes inherit from a single class ✅
Multiple One class inherits from multiple classes ❌ (Handled via interfaces)
Hybrid Combination of above Partially (via interfaces)
Inheritance
Inheritance is a feature by which new classes are derived from the existing classes.Inheritance
allows re-using code without having to rewrite from scratch. Inheritance is a compile-time
mechanism in Java that allows you to extend a class (called the base class or superclass) with
another class (called the derived class or subclass). In Java, inheritance is used for two purposes:
Class inheritance - create a new class as an extension of another class, primarily for the purpose
of code reuse. That is, the derived class inherits the public methods and public data of the base
class. Java only allows a class to have one immediate base class, i.e., single class inheritance
Interface inheritance – Interface inheritance is used to achieve multiple inheritance.
The Syntax for class inheritance is given below
[public ] class classname extends ParentClass
{
//variables and methods declaration
}
In keyword extends is used to implement inheritance in Java. In Java the following forms
of class inheritance is supported.
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance.
The program listed below is a single inheritance program.
class rectangle
{
int l;
int b;
rectangle(int x,int y)
{
l=x;
b=y;
}
void rect_area()
{
System.out.println(“Area of Rectangle is “ + l*b);
}
}
class cube extends rectangle
{
int h;
cube(int x,int y,int z)
{
super(x,y);
h=z;
}
void cube_volume()
{
System.out.println(“Volume of the Cube is “ + l*b*h);
}
}
class Mainprg
{
public static void main(String args[])
{
cube c=new cube(10,20,30);
c.rect_area();
c.cube_area();
}
}
Super Keyword
Java uses a unique keyword called “super” to call the super class constructers. In the previous
example we have used super keyword to pass parameters to the super class constructer from the
sub class constructer. The following is the syntax of super keyword
super() (or)
super(parameter list)
With super(), the superclass no-argument constructor is called. With super(parameter list), the
superclass constructor with a matching parameter list is called. The parameters in the super
keyword must match the parameters in the super class constructer When super keyword is used it
must be the first statement in the sub class constructor.
Multilevel Inheritance
As mentioned earlier java supports multilevel inheritance. The syntax for multilevel inheritance
is given below.
class super1
{
------
------
}
class sub1 extends super1
{
------
------
}
class sub2 extends sub1
{
------
------
}
2. Method Overriding
Same method name, same parameters in subclass
Runtime polymorphism
Overrides parent class behavior
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
3. super Keyword
Used for:
Calling parent class constructor
Accessing parent class method or variable
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calls parent method
System.out.println("Dog barks");
}
}
4. Dynamic Method Dispatch (Runtime Polymorphism)
Resolves method call at runtime not at compile-time
Uses parent class reference and child class object
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Meow");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Cat(); // Upcasting
a.sound(); // Calls Cat's sound() at runtime
}
}
5. Abstract Classes and Methods
Abstract class: Can have both abstract and concrete methods
Cannot be instantiated
Used for partial abstraction
abstract class Shape {
abstract void draw(); // Abstract method
void color() {
System.out.println("Color is red");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
6. Interfaces and Multiple Inheritance in Java
Interface is a contract: all methods are implicitly abstract and public
Java doesn't support multiple class inheritance, but multiple interfaces can be
implemented
interface Printable {
void print();
}
interface Showable {
void show();
}
class A implements Printable, Showable {
public void print() {
System.out.println("Printing");
}
public void show() {
System.out.println("Showing");
}
}
7. Java Packages and Access Modifiers
lang
io
image
util
JAVA
awt
applet peer
net
Using Java API Packages
In Java packages are organized in a hierarchical structure. The Java Package name consists of
words separated by periods. The first part of the name contains the name java. The remaining
words of the Java Package name reflect the contents of the package. The Java Package name also
reflects its directory structure. For example the statement
java.awt
represents the awt (Abstract Window Toolkit) package. As mentioned earlier the first part of the
package name starts with the word Java. The second part of the package name "awt" stands for
the contents of the package, in this case the Abstract Window Toolkit.
To import a class from the package into our program you have to use the import statement. The
syntax is
import packagename.classname
or
import packagename.*;
1. The first form of the syntax imports the specific class from the package .For example the
statement import java.util.Date imports the Date class available in the java.util package
into our program.
2. The second form of the syntax import all the classes available in the specified package.
For example java.io.* will import all the classes available in the io package.
User Defined Packages
You know that java supports a rich set of built in packages. Apart from these packages
Java allows us to create our own user defined packages. We can create our own package and use
it in our programs. Creation of package in java is easy. The various steps involved in creation of
package are listed below.
1. The package has to be declared at the beginning of the program. The syntax is
package packagename;
For example
package mypack;
2. The second step is to define classes and interfaces and put it inside the package. A
package can contain any number of classes; however one of the classes should have the
public access specifier. For example
package mypack
public class sample
//body of the class
3. Add methods and variables to class as required
4. Create a subdirectory with name of the package and put it under the current working
directory.
5. Save the class and compile the program.
A simple program to illustrate the creation of user defined package is given below.
package mypack;
public class sample
public sample()
System.out.println(“This is from the constructer”);
public void test()
System.out.println(“This is from the package mypack”);
Create a directory with the name mypack and put inside the current working directory. Save the
program with the name "sample.java” put in the sub directory mypack and compile the program.
Once a package is created, you can import the package and use it in your program. Consider the
code listing given below.
import mypack.sample
class Client
public static void main(String args[])
sample s=new sample();
s.test();
}
The program Client imports the classes from package mypack. The program “Client.java” should
be saved in the directory for which mypack is a subdirectory. After that compile and execute the
program
Visibility and Access Rights in Java
The table given below lists the visibility and access rights in java.
ACCESS RIGHTS FOR THE DIFFERENT SCOPES
CLASS\ACCESS PRIVATE DEFAULT PROTECTED PUBLIC SCOPE
RIGHTS SCOPE
SCOPE SCOPE
own class (Base) yes yes yes yes
subclass - same package no yes yes yes
(SubA)
class - same package no yes yes yes
(AnotherA)
subclass - another no no yes/no * yes
package (SubB)
class - another package no no no yes
(AnotherB)