Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

MODULE –

3
VRINDA A
Assistant Professor,
Dept. of IT, MESCE, Kuttippuram
Inheritance
• Inheritance is one of the features of Object-
Oriented Programming (OOP).

• Allows a class to use the properties and methods


of another class.
• Derived class inherits the states and behaviors from the
base class
• The derived class is also called subclass and the
base class is also known as super-class.
Inheritance
• The derived class can add its own additional variables
and methods.
• A super-class can have any number of subclasses. But
a subclass can have only one superclass.
• Thisis because Java does not support
multiple inheritance.

public class ChildClass extends BaseClass


{
// derived class methods extend and possibly override
}
Inheritance
• Notes:
• The derived class inherits all the attributes and methods
that are declared as public or protected. If declared as
private it can not be inherited by the derived classes.
• The private attributes can be accessed through assessor
methods – getters and setters

• The derived class cannot inherit an attribute of the


base class if the derived class declares
another attribute with the same name.
• All instances of subclass are instances of superclass
• Example
Inheritance
Generalization: process of forming a super class
Specialization: forming a subclass
Types of Inheritance in Java
• There are three types of inheritance in java:
• Single
• Multilevel
• hierarchical.

• In java programming, multiple and hybrid inheritance


is supported through interface only.
Types of Inheritance in Java
Constructors and Inheritance
• The constructor builds the object of a class
• The constructor in the superclass builds the object of the
superclass and the constructor in the subclass builds the
object of subclass.

• When the subclass constructor is called, it by


default invokes the default constructor of super-class.

• The superclass constructor can be called explicitly


using the keyword super
The ‘super’ Keyword
• A method to execute the super class constructor.
• The ‘super’ should be first statement in a constructor.

• The keyword super always refers to the


superclass immediately above of the calling
class in the hierarchy

• The use of multiple super keywords to access


an ancestor class other than the direct parent is
illegal.
• Example
Polymorphism
• One of the features of Object oriented programming.
• It is the ability of an object to take on many forms.
• Or, it is the capability of a method to do
different things based on the object that it is acting
upon.

• Here, an operation may exhibit different behavior


in different instances.
• The behavior depends on the types of data used in
the operation.
Polymorphism

• Following concepts demonstrate different types


of polymorphism in java.

• Method Overloading
• Method Overriding
Method Overloading
• In Java, it is possible to define two or more methods
of same name in a class, provided that there
argument list or parameters are different.

• When Java encounters a call to an overloaded method,


it simply executes the version of the method
whose parameters match the arguments used in
the call.

• It is also known as compile time polymorphism.


Method Overloading
class Overload { class MethodOverloading { public
void demo (int a) static void main (String
{ System.out.println ("a: " + a); args [ ])
} {
void demo (int a, int b) Overload Obj =
new Overload();
{ System.out.println ("a and b: "
double result;
+
a + "," + b); Obj.demo(10);
Obj.demo(10, 20);
}
result = Obj.demo(5.5);
double demo(double a)
{ System.out.println("double System.out.println("O/P
: "
a: " + result);
+ a);
}
return a*a;
}
}
Method Overloading

OUTPUT

a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Rules for Method Overloading

• Overloading can take place in the same class or in its


sub-class.

• Constructor in Java can be overloaded

• Overloaded methods must have a different


argument list.

• The parameters may differ in their type or number, or


in both.

• They may have the same or different return types.


Method Overriding
• Child class may have the same method as of base class.
In such cases child class overrides the parent
class method.
• Rules:
• applies only to inherited methods
• object type determines which overridden method will be
used at runtime
• overriding method can have different return type
• abstract methods must be overridden
• static and final methods cannot be overridden
• it is also known as Runtime polymorphism
Method Overriding
public class BaseClass { public class TestMethod {
public void methodToOverride() { public static void main (String
("I'm of the
System.out.println method args [ ]) {
BaseClass"); BaseClass obj1 =
} new BaseClass();

} // BaseClass reference
but DerivedClass object
public class
DerivedClass extends BaseClass BaseClass obj2 =
{ new DerivedClass();
obj1.methodToOverride();
public void
methodToOverride() obj2.methodToOverride();
{ }
System.out.println ("I'm the }
method of DerivedClass");
}
}
Method Overriding

OUTPUT

I'm the method of BaseClass I'm


the method of DerivedClass
super Keyword in Overriding
class Vehicle { public class TestCar {
public void move () { public static void main (String
System.out.println ("Vehicles args [ ]) {
are used for transportation "); Vehicle b =
} new C ar (); //
Vehicle reference();
b.move but//
Car objectthe
C alls
}
method in Car class
class Car extends Vehicle { public
}
void move () {
}
super. move (); // invokes the
super class method
When invoking a superclass
System.out.println ("C ar is version of an overridden
a good medium of transport
");
method the super keyword is
used.
}
}
super keyword in Overriding

OUTPUT

Vehicles are used for transportation


Car is a good medium of transport
Dynamic Method Dispatch
• Method overriding is one of the ways in which Java
supports Runtime Polymorphism.
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run
time, rather than compile time.

• When an overridden method is called through a


superclass reference, Java determines
which version(superclass/subclasses) of that
method is to be executed based upon the type of the
object.
Dynamic Method Dispatch
• At run-time, it depends on 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

• A superclass reference variable can refer to a subclass


object. This is also known as upcasting.
• Java uses this fact to resolve calls to overridden
methods at run time.
Dynamic Method Dispatch
Abstract Classes and Inheritance
• The super classes are more general than
their subclasses.

• Usually, the super classes are made abstract so that the


objects of its prototype cannot be made.
• The objects of only the subclasses can be used.

• To make a class abstract, the keyword abstract is used


in the class definition.
• The abstract class cannot be instantiated because it does
not define a complete implementation.
Abstract Classes and Inheritance
public abstract class Parent
{
….
}
class Child extends Parent
{
……
}
final with Inheritance
• We can prevent a class from being inherited by using the
keyword final at the start of its declaration.

• An abstract class cannot be declared as final because an


abstract class is incomplete and its subclasses need to
provide the implementation.
final with Inheritance
class rectangle extends shape
final class shape
{
{ // The type rectangle cannot
void showattributes() subclass the final class shape
void showattributes() {
{
System.out.println("Inside
class rectangle");
System.out.println("Inside }
class shape "); }
}
}

The class shape cannot be inherited because it is declared as


final. It will show an error when we try to inherit it
Packages
• A package can be defined as a group of related classes.
• It provides access protection and name
space management.
• Some of the existing packages in Java are:
• java.lang - bundles the fundamental classes
• java.io - classes for input, output functions

• Programmers can define their own packages to bundle


group of classes
Packages
• While creating a package
• choose a name for the package
• include a package statement along with that name

• The package statement should be the first line in


the source file

• There can be only one package statement in


each source file

• Always use lower case letters for package name


to avoid any conflicts with the names of classes.
Packages
Elephant.java package animals;
For example, Cat.java public class Elephant{
package animals; public void eat()
public class Cat{ { System.out.println("Elephant
public void run() eats");
}
{ System.out.println("Cat runs"); }
public void travel(){
public void walk(){ System.out.println("Elephant
System.out.println("Cat walks"); } travels");
public static void main(String args[]) }
public static void main(String args[])
{ Cat c = new Cat();
{ Elephant e = new Elephant();
c.run(); e.eat();
c.walk(); e.travel();
} }
}
}
Packages
• Now compile the java files as shown below:
javac -d . Cat.java javac -d .
Elephant.java

• Now a package/folder with the name animals will be


created in the current directory and these class files will be
placed in it.
• You can execute the class file within the package as

java animals.Cat or
java animals.Elephant
Packages
• If a class wants to use another class in the same package, the
package name does not need to be used.
• Classes in the same package find each other without any special
syntax.
For example • Here, a class named Boss
package payroll; is added to the
public class Boss{ package that already
payroll
public void payEmployee(Employee e)
contains Employee.
{ • The Boss can then
e.mailCheck(); refer
to the Employee class
} without using the payroll
prefix
}
Packages
• What happens if the Employee class is not in the
payroll package?
• The Boss class must then use one of the
following techniques for referring to a class in a different
package.

1. Thefully qualified name of the class can be


used.
payroll.Employee

2. The package can be imported using the import keyword and the
wild card (*)
import payroll.*;
Interfaces
• An interface in java is a blueprint of a class.
• Writing an interface is similar to writing a class.

• It has static constants and abstract methods only.


• Class describes the attributes and behaviors of an object.
Whereas interface contains behaviors that a class
implements.
• The interface in java is a mechanism to achieve fully
abstraction and multiple inheritance.
• There can be only abstract methods in the java interface not
method body.
• Example: InterfaceEg.java
Interfaces
• An interface is different from a class in several ways:
• We cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface is not extended by a class; it is implemented by
a class.
• A class can extend only from one class, but implement many
interfaces.
• An interface can extend interfaces or
another interfaces. multiple
• Example: MultipleInterface.java
Interfaces Vs Classes
• A class extends another class, an interface extends another
interface but a class implements an interface.
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface
extends multiple interfaces i.e. known as multiple
inheritance.
Nested Interface
• An interface can have another interface i.e. known
as nested interface.
• For example,
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}

You might also like