UNIT3
UNIT3
UNIT3
INHERITANCE: Inheritance Basics, Types of Inheritance, The Keyword ‘super’, Final with
inheritance.
POLYMORPHISM: Method Overriding, Dynamic Method Dispatch, Abstract Classes.
INTERFACES: Interface, Multiple Inheritance using Interface, Abstract Classes vs. Interfaces.
INHERITANCE
The process of obtaining the data members and methods from one class to another class is
known as inheritance. It is one of the fundamental features of object-oriented programming.
Important points
In the inheritance the class which gives data members and methods is known as base
or super or parent class.
The class which is taking the data members and methods is known as sub or derived
or child class.
The concept of inheritance is also known as re-usability or extendable classes or sub
classing or derivation.
Syntax of Inheritance
Advantage of inheritance
If we develop any application using concept of Inheritance than that application have
following advantages,
Application development time is less.
Application takes less memory.
Application execution time is less.
Application performance is enhance (improved).
Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.
Types of Inheritance
Based on number of ways inheriting the feature of base class into derived class we have five
types of inheritance; they are:
Single inheritance
Multiple inheritance
Hierarchical inheritance
Multilevel inheritance
Hybrid inheritance
SINGLE INHERITANCE
In single inheritance there exists single base class and single derived class.
EXAMPLE:
class Employee
{
float salary=60000;
}
class Science extends Employee
{
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}
}
OUTPUT:
MULTILEVEL INHERITANCES
In Multilevel inheritances there exists single base class, single derived class and multiple
intermediate base classes.
EXAMPLE:
class Employee
{
float total_sal=0, salary=50000;
}
OUTPUT:
MULTIPLE INHERITANCE
In multiple inheritance there exist multiple classes and single derived class.
The concept of multiple inheritance is not supported in java through concept of classes but it can
be supported through the concept of interface.
HYBRID INHERITANCE
In the combination if one of the combination is multiple inheritance then the inherited
combination is not supported by java through the classes concept but it can be supported through
the concept of interface.
EXAMPLE:
SUPER KEYWORD
The super keyword in java is a reference variable that is used to refer immediate parent
class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
EXAMPLE:
class Employee
{
float salary=10000;
}
class HR extends Employee
{
float salary=20000;
void display()
{
System.out.println("Salary: "+super.salary);//print base class salary
}
}
class Supervarible
{
public static void main(String[] args)
{
HR obj=new HR();
obj.display();
}
}
OUTPUT:
Salary: 10000.0
EXAMPLE:
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
OUTPUT:
EXAMPLE:
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}
OUTPUT:
When a class hierarchy is created, in what order are the constructors for the classes that make up
the hierarchy called? For example, given a subclass called B and a superclass called A, is A’s
constructor called before B’s, or vice versa? The answer is that in a class hierarchy, constructors
are called in order of derivation, from superclass to subclass. Further, since super( ) must be the
first statement executed in a subclass’ constructor, this order is the same whether or not super( )
is used. If super( ) is not used, then the default or parameterless constructor of each superclass
will be executed
EXAMPLE:
OUTPUT :
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
METHOD OVERRIDING
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the
version of that method defined by the subclass.
// 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;
}
OUTPUT
k: 3
Rules for Method Overriding in Java
The access level can't be more restrictive than the overridden method's
Private Methods cannot be Overridden
Overriding Method must have the same return type (or Covariant return type)
You cannot override constructor as the constructor name of the base class and child class
can never be same
ABSTRACT CLASSES
A class that is declared with abstract keyword is known as abstract class in java.
To declare a class abstract, you simply use the abstract keyword in front of the
class keyword at the beginning of the class declaration.
There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator.
Such objects would be useless, because an abstract class is not fully defined.
Any sub-class extending from an abstract class should either implement all the abstract
methods of the super-class or the sub-class itself should be marked as abstract
It is not necessary to add the abstract methods only in the super most class, we can add
more abstract methods in the sub-classes.
EXAMPLE:
abstract class A {
abstract void callme();
While method overriding is one of Java’s most powerful features, there will be times
when you will want to prevent it from occurring.
To disallow a method from being overridden, specify final as a modifier at the start of its
declaration.
EXAMPLE:
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!");
}
}
USING FINAL TO PREVENT INHERITANCE
EXAMPLE:
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Dynamic method dispatch is important because this is how Java implements run-time
polymorphism
When different types of objects are referred to, different versions of an overridden
method will be called.
In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
EXAMPLE:
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
r = a; // r refers to an A object
r = b; // r refers to a B object
OUTPUT:
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
The interface is a mechanism to achieve fully abstraction in java. There can be only abstract
methods in the interface. It is used to achieve fully abstraction and multiple inheritance in
Java.
properties of Interface
DEFINING AN INTERFACE
An interface is defined much like a class. This is the general form of an interface:
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
EXAMPLE:
interface Callback {
void callback(int param);
}
IMPLEMENTING INTERFACES
// class-body
}
EXAMPLE :
interface Animal {
}
}
OUTPUT:
ammal eats
ammal travels
One interface can inherit another by use of the keyword extends. The syntax is the
same as for inheriting classes. When a class implements an interface that inherits
another interface, it must provide implementations for all methods defined within
the interface inheritance chain
EXAMPLE:
OUTPUT:
Implement meth1().
Implement meth2().
Implement meth3()
interface AnimalEat {
void eat();
}
interface AnimalTravel {
void travel();
}
class Animal implements AnimalEat, AnimalTravel {
public void eat() {
System.out.println("Animal is eating");
}
public void travel() {
System.out.println("Animal is travelling");
}
}
public class Demo {
public static void main(String args[]) {
Animal a = new Animal();
a.eat();
a.travel();
}
}
OUTPUT:
Animal is eating
Animal is travelling
DIFFERENCE BETWEEN CLASS AND INTERFACE