You are on page 1of 12

Java KT Session 1

By Himabindu
Inheritence

Oops Encapsulation
Concepts Abstraction

Polymorphism
Definition:
Acquiring the properties of one Class by
another class is inheritance.
• Base Class-Derived Class
• Parent Class-Child Class
Inheritance Inheritence can be implemented by using
“extends” Keyword.
Advantages:
Code reusability.
Method Overriding.
Syntax for Inheritance
class​superclass
{
 // superclass data variables
 // superclass member functions
}
class​subclass ​extends​superclass
{
 // subclass data variables
 // subclass member functions
}
Case 1: Case2: Case3: Case4:
On parent class On Child class Parent class Child class
reference Child reference Parent reference can be reference cannot
specific methods or and child specific used to hold child be used to hold
variables cannot be methods or class object but parent class object
called. variables can be Child specific Child c=new
Parent p=new called. methods cannot be p(); //Compile time
Parent(); Child c=new called. error
p.parentMethod(); Child(); Parent p=new
c.parentMethod(); child();
p.childMethod();
c.childMethod(); p.parentMethod();
// this will give
compile time error p.childMethod();
Example:
class Base
 {
 public void M1()
 { Output:
 System.out.println(“ Base Class Method ”);
 }
 }
class Derived extends Base
{
 public void M2()
 {
 System.out.printIn(“ Derived Class Methods “);
 }
}
class Test
{
 public static void main(String[] args)
 {
 Derived d = new Derived(); // creating object
 d.M1(); // print Base Class Method
 d.M2(); // print Derived Class Method
 }
}
Types Of Inheritance
• Single Inheritance
• Multiple Inheritance(Not available in java)
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance Example
class A
{
 int a, b;
 void display()
 {
 System.out.println(“Inside class A values =”+a+” ”+b);
 }
}
class B extends A
{
 int c;
 void show()
 {
 System.out.println(“Inside Class B values=”+a+” “+b+” “+c);  }
}
class SingleInheritance
{
 public static void main(String args[])
{
 B obj = new B(); //derived class object
 obj.a=10;
 obj.b=20;
 obj.c=30;
 obj.display();
 obj.show();
 }
}
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Queries & Thank you

You might also like