0% found this document useful (0 votes)
3 views77 pages

Session 20 Inheritance

The document discusses key concepts in object-oriented programming, focusing on inheritance, encapsulation, abstraction, and polymorphism. It explains the importance of data hiding for security, the benefits of encapsulation for maintainability, and the role of inheritance in promoting code reusability. Additionally, it covers method overloading, the characteristics of abstract classes, and the distinctions between composition and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views77 pages

Session 20 Inheritance

The document discusses key concepts in object-oriented programming, focusing on inheritance, encapsulation, abstraction, and polymorphism. It explains the importance of data hiding for security, the benefits of encapsulation for maintainability, and the role of inheritance in promoting code reusability. Additionally, it covers method overloading, the characteristics of abstract classes, and the distinctions between composition and aggregation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 77

Session 20 Inheritance

Dr. Naveen Kumar


Associate Professor
Amity Institute of Information Technology
Amity University Patna

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Data Hinding
• Data members (Internal data) should not be accesses
outside directly that is outside person can't access our
internal data directly.
• By using private modifier we can implement data hiding.
Example:
class Account {
private double balance;
......................;
......................;
}
• After providing proper username and password only , we
can access our Account information.
• The main advantage of data hiding is security.

• Note: recommended modifier for data members is


private.
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Abstraction
• Hide internal members and just highlight the set of
abstraction.
necessary services, is called
• By using abstract classes and interfaces we can
implement abstraction. Example :
• By using ATM GUI screen bank people are highlighting the
set of services what they are offering without highlighting
internal implementation.
• The main advantages of Abstraction are:
1. We can achieve security as we are not highlighting our
internal implementation.(i.e., outside person doesn't
aware our internal implementation.)
2. Enhancement will become very easy because without
effecting end user we can be able to perform any type of
changes in our internal system.
3. It provides more flexibility to the end user to use system
very easily.
4. It improves maintainability of the application.
Dr. Naveen Kumar, Associate
5. It improves modularity Professor,
of theAIIT,
application.
AUP
Encapsulation
• Binding of data and corresponding methods into a single
unit is called Encapsulation .
• If any java class follows data hiding and abstraction such
type of class is said to be encapsulated class.

Encapsulation=Datahiding+Abstraction

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Every data member should be declared as private and for
every member we have to maintain getter & Setter
methods.

• The main advantages of encapsulation are :


1. We can achieve security.
2. Enhancement will become very easy.
3. It improves maintainability and modularity of the
application.
4. It provides flexibility to the user to use system very easily.

• The main disadvantage of encapsulation is it increases


length of the code and slows down execution.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Tightly Encapsulated Class
• A class is said to be tightly encapsulated if and only if
every variable of that class declared as private whether
the variable has getter and setter methods are not , and
whether these methods declared as public or not, these
checking are not required to perform.
• Example:
class Account {
private double balance;
public double getBalance() {
return balance;
}
}
• Which of the following classes are tightly
encapsulated?

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Which of the following classes are tightly encapsulated?
• class A { int x=10; //not
• }

• class B extends A {
• private int y=20; //not
• }

• class C extends B {
• private int z=30; //not
• }

• Note: if the parent class is not tightly encapsulated then


no child class is tightly encapsulated.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Inheritance
• IS-ARelationship(inheritance):
1) Also known as inheritance.
2) By using extends keywords we can implement IS-A
relationship.
3) The main advantage of IS-A relationship is reusability.
• class Parent
{
public void methodOne()
• { }
• }

• class Child
• {
• Public void methodTwo()
• { }
• }
Dr. Naveen Kumar, Associate Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Interpretation
• 1) Whatever members the parent has by default available to the
child but whatever members the child has by default not available to
the parent.
• Hence on the child reference we can call both parent
and child class methods.

• But on the parent reference we can call only methods available


in the parent class and we can’t call child specific methods.
2) Parent class reference can be used to hold child class object but
by using that reference we can call only methods available in parent
class and child specific methods we can’t call.
3) Child class reference cannot be used to hold parent class object.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• The common methods which are required
for housing loan, vehicle loan, personal
loan and education loan we can define
into a separate class in parent class loan.
• So that automatically these methods are
available to every child loan class.

• This is due to Reusability

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• class Loan
{
//common methods which are required for any type of
loan.
}
class HousingLoan extends Loan
• {
//Housing loan specific methods.
}
class EducationLoan extends Loan
{
//Education Loan specific methods.
}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
• For all java classes the most commonly required functionality is
define inside Object class hence Object class acts as a root for all
java classes.
• For all java exceptions and errors the most common required
functionality defines inside Throwable class hence Throwable
class acts as a root for exception hierarchy.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Multiple Inheritance
• Having more than one Parent class at the same level is
called multiple inheritance.

• Any class can extends only one class at a time and can't
extends more than one class simultaneously hence java
won't provide support for multiple inheritance.

• But an interface can extends any no. Of interfaces at a


time hence java provides support for multiple inheritance
through interfaces.
• If our class doesn't extends any other class then only our
class is the direct child class of object.

• If our class extends any other class then our class is not
direct child class of object, It is indirect child class of
object , which forms multilevel inheritance.

• Why java won't provide support for multiple inheritance?


There may be a chance of raising ambiguity problems.
• Why ambiguity problem won't be there in interfaces?
• Interfaces having dummy declarations and they won't have
implementations hence no ambiguity problem.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Cyclic Inheritance
• Cyclic inheritance is not allowed in java.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
HAS-A Relationship
1. HAS-A relationship is also known as composition (or)
aggregation.
2. There is no specific keyword to implement HAS-A
relationship but mostly we
3. can use new operator.
4. The main advantage of HAS-A relationship is reusability.
• class Engine
• {
• //engine specific functionality
• }
• class Car {
• Engine e=new Engine();
• //........................;
• //........................;
• //........................;
• }
• class Car HAS-A engine reference.
• The main dis-advantage of HAS-A relationship increases
dependency between
Composition vs Aggregation:
• Composition:
• Without existing container object if there is no chance of
existing contained objects then the relationship between
container object and contained object is called composition
which is a strong association.
• Example:
• University consists of several departments whenever
university object destroys automatically all the
department objects will be destroyed that is without
existing university object there is no chance of existing
dependent object hence these are strongly associated and
this relationship is called composition.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Aggregation
• Aggregation :
• Without existing container object if there is a chance of
existing contained objects such type of relationship is
called aggregation. In aggregation objects have weak
association.
• Example:
• Within a department there may be a chance of several
professors will work whenever we are closing department
still there may be a chance of existing professor object
without existing department object the relationship
between department and professor is called aggregation
where the objects having weak association.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Note :
• In composition container , contained objects are strongly
associated, and but container object holds contained
objects directly
But in Aggregation container and contained objects are
weakly associated and container object just now holds the
reference of contained objects.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Method Signature
• In java, method signature consists of name of the method
followed by argument types.

• In java return type is not part of the method signature.


•  Compiler will use method signature while resolving
method calls.
• Within the same class we can't take 2 methods with the
same signature otherwise we will get compile time error.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Polymorphism
• Same name with different forms is the concept of
polymorphism.
Example 1: We can use same abs() method for int type,
long type, float type etc.
• Example:
• 1. abs(int)
• 2. abs(long)
• 3. abs(float)
• Example 2:
We can use the parent reference to hold any child objects.
We can use the same List reference to hold ArrayList
object, LinkedList object, Vector object, or Stack object.
• Example:
1. List l=new ArrayList();
2. List l=new LinkedList();
3. List l=new Vector();
4. List l=new Stack();
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Most Important Features

1) Inheritance talks about reusability.


2) Polymorphism talks about flexibility.
3) Encapsulation talks about security.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Method Overloading
• Two methods are said to be overload if and only if both
having the same name but different argument types.
• In java we can take multiple methods with the same name
and different
• argument types.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Abstract class is declared with the
abstract keyword.
• It may have both abstract and non-
abstract methods(methods with
bodies).
• An abstract is a Java modifier
applicable for classes and methods
in Java but not for Variables.
abstract class Shape
{
int color;
// An abstract function
Dr. Naveen Kumar, Associate
abstract void draw(); Professor, AIIT, AUP
1. An instance of an abstract class can not be created.
2. Constructors are allowed.
3. We can have an abstract class without any abstract
method.
4. There can be a final method in abstract class but any
abstract method in class(abstract class) can not be
declared as final or in simpler terms final method can not
be abstract itself as it will yield an error: “Illegal
combination of modifiers: abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level
classes (Outer class) as well as inner classes as
abstract
7. If a class contains at least one abstract method then
compulsory should declare a class as abstract
8. If the Child class is unable to provide
Dr. Naveen Kumar, Associate implementation to all
abstract methods of theProfessor,
Parent class then we should
AIIT, AUP
1. Example of Abstract Class
that has Abstract method
//Abstract class
abstract class Sunstar {
abstract void printInfo();
}

//Abstraction performed using extends


class Employee extends Sunstar {
void printInfo()
{
String name = "avinash";
int age = 21;
float salary = 222.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}

//Base class
class Base {
public static void main(String args[])
{
Sunstar s = new Employee();
s.printInfo();
} Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
2. Abstract Class having
constructor, data member, and
methods
• Elements abstract class can have
• data member
• abstract method
• method body (non-abstract method)
• constructor
• main() method.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
//Implement Abstract Class having constructor, data member, and methods
abstract class Subject {
Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus();

void Learn(){
System.out.println("Preparing Right Now!");
}
}

class IT extends Subject {


void syllabus(){
System.out.println("C , Java , C++");
}
}

class Demo {
public static void main(String[] args) {
Subject x=new IT();
x.syllabus();
x.Learn();
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Properties of Abstract class
• 1. we can have references to
abstract class type but not object.
//Abstract class
abstract class Base {
abstract void fun();
}

class Derived extends Base {


void fun()
{
System.out.println("Derived fun() called");
}
}

class Main {
public static void main(String args[])
{
//Base b = new Base();
// but We can have references of Base type.
Base b = new Derived();
b.fun();
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• 2. an abstract class can
contain constructors in Java. And a
constructor of an abstract class is
called when an instance of an
inherited class is created.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
//Abstract class
abstract class Base { class Demo {
public static void main(String
// Constructor of abstract class args[])
Base() {
{
System.out.println("Base Constructor Called"); // Creating object of Derived inside
} main() method
Derived d = new Derived();
// Abstract method inside abstract class d.fun();
abstract void fun(); }
} }

class Derived extends Base {

// Constructor of Derived class


Derived()
{
System.out.println("Derived Constructor Called");
}

// implemented method of class2


void fun()
{
System.out.println("Derived fun() called");
}
}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
3. We can have abstract class
without any abstract method.
This allows us to create classes that
cannot be instantiated but can
only be inherited.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
class Main {
//An abstract class without
any abstract method public static void main(String
abstract class Base { args[])
//This is not an abstract method. {
void fun() Derived d = new Derived();
{ d.fun();
System.out.println("Base class }
fun() is called"); }
}
}

class Derived extends Base {


// This class only inherits the
Base class methods and
// properties
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Abstract classes can also
have final methods (methods that
cannot be overridden)

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
•abstract class Base {
•final void fun()
•{
•System.out.println("Base fun() called");
•}
•}

•class Derived extends Base {

•}

•class Demo {
•public static void main(String args[])
•{
•Base b = new Derived();
•b.fun();
•}
•}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
• an abstract class instantiation is not
possible.
abstract class AbstractClass {
public static void main(String args[])
{
// Trying to create an object
AbstractClass gfg = new AbstractClass();
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• we can define static methods in
an abstract class that can be
called independently without an
object.
abstract class Helper {
static void demofun()
{
System.out.println("Geeks for Geeks");
}
}

public class Derived extends Helper {


public static void main(String[] args)
{
Helper.demofun();
} Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
• We can use the abstract
keyword for declaring top-level
classes (Outer class) as well as inner
classes as abstract
abstract class B {
// inner class as abstract
abstract class C {
abstract void myAbstractMethod();
}
}
class D extends B {
class E extends C {
// implementing the abstract method
void myAbstractMethod()
{
System.out.println(
"Inside abstract method implementation");
Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
•public class Main {

•public static void main(String args[])


•{
•// Instantiating the outer class
•D outer = new D();

•// Instantiating the inner class


•D.E inner = outer.new E();
•inner.myAbstractMethod();
•}
•}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• If a class contains at least one
abstract method then compulsory
we should declare the class as
abstract otherwise we will get a
compile-time error.
• we should use abstract keyword.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
abstract class Base {
abstract void m1();
}

class Child extends Base {


public void m1()
{
System.out.print("Hello");
}
}
class Demo {
public static void main(String[] args)
{
Child c = new Child();
c.m1();
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• If the Child class does not provide
implementation to all abstract
methods of the Parent class then we
should declare that Child class as
abstract so that the next level Child
class should provide implementation
to the remaining abstract method.
abstract class Base {
abstract void m1();
abstract void m2();
abstract void m3();
Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
•abstract class FirstChild extends Base {
•public void m1() {
•System.out.println("Inside m1");
•}
•}

•class SecondChild extends FirstChild {


•public void m2() {
•System.out.println("Inside m2");
•}
•public void m3() {
•System.out.println("Inside m3");
•}
•}

•class Demo {
•public static void main(String[] args)
•{
•// FirstChild f=new FirstChild();
•// f.m1();

•SecondChild s = new SecondChild();


•s.m1();
•s.m2();
•s.m3();
•}
•}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Interface
• An Interface is an abstract type used to
specify the behavior of a class.
• An interface in Java is a blueprint of a
behavior.
• A Java interface contains static constants
and abstract methods.
• a mechanism to achieve abstraction and
multiple Inheritance.
• Traditionally, an interface could only have
abstract methods (methods without a
body) and public, static, and final variables
by default. Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
• When we decide on a type of entity by its
behavior and not via attribute we should
define it as an interface.
• interface {
// declare constant fields
// declare methods that abstract
// by default.
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Uses of Interfaces in Java are mentioned below:
• It is used to achieve total abstraction.
• Since java does not support multiple inheritances in the
case of class, by using an interface it can achieve
multiple inheritance.
• Any class can extend only one class, but can implement
multiple interfaces.
• It is also used to achieve loose coupling.
• Interfaces are used to implement abstraction.
• abstract classes may contain non-final variables, whereas
variables in the interface are final, public, and static.
• // A simple interface
interface Player
{
final int id = 10;
int move(); Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Class vs Interface

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Class Interface

In an interface, you must initialize


In class, you can instantiate variables
variables as they are final but you
and create an object.
can’t create an object.

A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.

The access specifiers used with


In Interface only one specifier is used-
classes are private, protected, and
Public.
public.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Abstract Class vs Interface
Points
Abstract Class Interface

Cannot be instantiated; contains


Specifies a set of methods a class
both abstract (without
Definition implementation) and concrete
must implement; methods are
abstract by default.
methods (with implementation)

Implementation Methods are abstract by default;


Can have both implemented and
Java 8, can have default and static
Method abstract methods.
methods.

class can inherit from only one A class can implement multiple
Inheritance abstract class. interfaces.

Access Methods and properties can have


Methods and properties are
any access modifier (public,
Modifiers implicitly public.
protected, private).

Can have member variables (final, Variables are implicitly public, static,
Variables non-final, static, non-static). and final (constants).

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Abstract Class
• An abstract class is a class that cannot be instantiated
directly. It serves as a blueprint for other classes to derive
from.

• An abstract class can contain both abstract methods


(methods without an implementation) and concrete
methods (methods with an implementation).

• Abstract classes can have member variables, including


final, non-final, static, and non-static variables.

• Abstract classes can have constructors, which can be


used to initialize variables in the abstract class when it is
instantiated by a subclass.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
//A simple interface
interface In1 {
// public, static and final
final int a = 10;

// public and abstract


void display();
}

//A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
interface Vehicle {
void changeGear(int a);
void speedUp(int a);
void applyBrakes(int a);
}
class Bicycle implements Vehicle{
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
}
}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
class Bike implements Vehicle {
int speed;
int gear;
// to change gear
@Override
public void changeGear(int newGear){
gear = newGear;
}
// to increase speed
@Override
public void speedUp(int increment){
speed = speed + increment;
}
// to decrease speed
@Override
public void applyBrakes(int decrement){
speed = speed - decrement;
}
public void printStates() {
System.out.println("speed: " + speed
+ " gear: " + gear);
} Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
class Demo {
public static void main (String[] args) {
// creating an instance of Bicycle
// doing some operations
Bicycle bicycle = new Bicycle();
bicycle.changeGear(2);
bicycle.speedUp(3);
bicycle.applyBrakes(1);
System.out.println("Bicycle present state :");
bicycle.printStates();
// creating instance of the bike.
Bike bike = new Bike();
bike.changeGear(1);
bike.speedUp(4);
bike.applyBrakes(3);
System.out.println("Bike present state :");
bike.printStates();
}
} Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
//Interface 1
interface API {
default void show()
{
System.out.println("Default API");
}
}

//Interface 2
//Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}

//Interface 3
//Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}

public static void main(String args[])


{
TestClass d = new TestClass();
d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
} Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
interface A {
void method1();
void method2();
}
// B now includes method1 and method2
interface B extends A {
void method3();
}
// the class must implement all method of A and B.
class ClassA implements B {
public void method1()
{
System.out.println("Method 1");
}
public void method2()
{
System.out.println("Method 2");
}
public void method3()
{
System.out.println("Method 3");
}
}

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
//Level 1
interface Bank {
void deposit();
void withdraw();
void loan();
void account();
}

//Level 2
abstract class Dev1 implements Bank {
public void deposit()
{
System.out.println("Your deposit Amount :" + 100);
}
}

abstract class Dev2 extends Dev1 {


public void withdraw()
{
System.out.println("Your withdraw Amount :" + 50);
}
} Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
//Level 3
class Dev3 extends Dev2 {
public void loan() {}
public void account() {}
}

//Level 4
class Demo {
public static void main(String[] args)
{
Dev3 d = new Dev3();
d.account();
d.loan();
d.deposit();
d.withdraw();
}
} Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Super keyword
• Characteristics of Super Keyword in J
ava
• Use of super keyword in Java
• 1. Use of super with Variables
• 2. Use of super with Methods
• 3. Use of super with constructors
• Advantages of Using Java Super Key
word

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
Characteristics of super
• super is used to call a superclass constructor:
• When a subclass is created, its constructor must call the
constructor of its parent class. This is done using the
super() keyword, which calls the constructor of the parent
class.
• super is used to call a superclass method:
• A subclass can call a method defined in its parent class
using the super keyword. This is useful when the subclass
wants to invoke the parent class’s implementation of the
method in addition to its own.
• super is used to access a superclass field:
• A subclass can access a field defined in its parent class
using the super keyword. This is useful when the subclass
wants to reference the parent class’s version of a field.
• super must be the first statement in a constructor:
• When calling a superclass
Dr. Naveenconstructor,
Kumar, Associate the super()
statement must be the Professor,
first statement
AIIT, AUP
in the constructor of
• super cannot be used in a static context:
• The super keyword cannot be used in a static
context, such as in a static method or a static
variable initializer.
• super is not required to call a superclass
method:
• While it is possible to use the super keyword to
call a method in the parent class, it is not
required. If a method is not overridden in the
subclass, then calling it without the super
keyword will invoke the parent class’s
implementation.

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
• Use of super keyword in Java
• It is majorly used in the following
contexts as mentioned below:
1. Use of super with Variables
2. Use of super with Methods
3. Use of super with Constructors

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
//Base class vehicle
class Vehicle {
int maxSpeed = 120;
}

//sub class Car extending vehicle


class Car extends Vehicle {
int maxSpeed = 180;

void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}

//Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
} Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
class Person {
void message()
{
System.out.println("This is person class\n");
}
}
class Student extends Person {
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
message(); //call current class message() method
super.message(); //call parent class message() method
}
}
//Driver Program
class Test {
public static void main(String args[])
{
Student s = new Student();
s.display(); // calling display() of Student
} Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
class Person {
Person()
{
System.out.println("Person class Constructor");
}
}
//subclass Student extending the Person class
class Student extends Person {
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
//Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
Dr. Naveen Kumar, Associate
} Professor, AIIT, AUP
Advantages of Super
Keyword
• Enables reuse of code:
• Using the super keyword allows subclasses to inherit functionality from
their parent classes, which promotes the reuse of code and reduces
duplication.
• Supports polymorphism:
• Because subclasses can override methods and access fields from their
parent classes using super, polymorphism is possible. This allows for more
flexible and extensible code.
• Provides access to parent class behaviour:
• Subclasses can access and use methods and fields defined in their parent
classes through the super keyword, which allows them to take advantage
of existing behaviour without having to reimplement it.
• Allows for customization of behaviour:
• By overriding methods and using super to call the parent implementation,
subclasses can customize and extend the behaviour of their parent classes.
• Facilitates abstraction and encapsulation:
• The use of super promotes encapsulation and abstraction by allowing
subclasses to focus on their behaviour while relying on the parent class to
handle lower-level details.
Dr. Naveen Kumar, Associate
Professor, AIIT, AUP
Anonymous Class

Dr. Naveen Kumar, Associate


Professor, AIIT, AUP
THANK
YOU

Dr. Naveen Kumar, Associate Professor, AIIT, AUP

You might also like