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

Relationships : Association , Aggregation

, Inheritance , super keyword

Dr B.Veera Jyothi
IT Department , CBIT.
Inheritance (IS-A relationship) in Java

 Inheritance is one of the key features of Object Oriented Programming.

 Inheritance provided mechanism that allowed a class to inherit property of

another class. When a Class extends another class it inherits all non-private

members including fields and methods.

 Inheritance in Java can be best understood in terms of Parent and Child

relationship, also known as Super class(Parent) and Sub class(child) in Java

language.
Inheritance (IS-A relationship) in Java

• To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.

class Vehicle
{

......
}

class Car extends Vehicle

....... //extends the property of vehicle class

}
Inheritance (IS-A relationship) in Java

• Purpose of Inheritance

• It promotes the code reusability i.e. the same methods and variables which
are defined in a parent/super/base class can be used in the
child/sub/derived class.
• It promotes polymorphism by allowing method overriding.

• Disadvantages of Inheritance

• Main disadvantage of using inheritance is that the two classes gets tightly


coupled.
• This means that if we change code of parent class, it will affect to all the
child classes which is inheriting/deriving the parent class, and hence, it
cannot be independent of each other.
Member Access and Inheritance

 A subclass includes all of the members of its super class, it cannot access
those members of the super class that have been declared as private.
Inheritance relationship in Java language is
• Association
• Is-A
• Has-A
• None
Output of following Java Program?
Java Inheritance    

class Base {
    public void show() { 1.Derived:show() called
       System.out.println("Base::show() called");
    } 2.Base:show() called
} 3. None of the above
  
class Derived extends Base {
    public void show() {
       System.out.println("Derived::show() called");
    }
}
  
public class Main {
    public static void main(String[] args) {
        Base b = new Derived();;
        b.show();
    }
}
Using super

 Whenever a subclass needs to refer to its immediate


superclass, it can do so by use of the keyword super.
 super has two general forms. The first calls the super class
constructor.
 The second is used to access a member of the super class
that has been hidden by a member of a subclass.
super( arg-list);

super.member
 Here, member can be either a method or an instance variable.

You might also like