UNIT-II�(PART-I)
INHERITANCE (EXTENDING AND IMPLEMENTING)
TOPICS:
INHERITANCE
Definition :The mechanism in which one object acquires all the properties and behaviors of a parent object.
Derived Class : A Derived (Sub Class) is defined as
Syntax :
Advantages of Inheritance:
Code Reusability :
Eg: /* Inheritance Sample Example */
O/P : Programmer salary is:40000.0
Bonus of programmer is:10000
Types of Inheritances : There are various types of Inheritances in Java.
1. Single Inheritance: Derivation of sub class from only one super class is called “ Single Inheritance “.
Eg-1: /* Single Inheritance Example */
O/P : barking
eating
Eg-2: /* Single Inheritance Example */
Contd…
Contd…
/* SINGLE INHERITANCE */
class A
{
int a=10;
void Adisplay()
{
System.out.println("CLASS A");
}
}
class B extends A
{
int b=20;
void Bdisplay()
{
System.out.println("CLASS A");
}
}
class Single
{
public static void main(String a[])
{
B obj2=new B();
System.out.println("obj1.a="+obj2.a);
obj2.Adisplay();
System.out.println("obj2.b="+obj2.b);
obj2.Bdisplay();
}
}
2. Multi Level Inheritance: Derivation of a class from another derived class is called “ Multi Level Inheritance “.
Eg-2: /* Multi Level Inheritance Example */
Contd…
/* MULTILEVEL INHERITANCE*/
class P
{
int a=10;
void display()
{
System.out.println("A");
}
}
class C extends P
{
int b=20;
void dis()
{
System.out.println("B");
}
}
class CChild extends C
{
int c=30;
void show()
{
System.out.println("C");
}
}
class MultilevelInherit
{
public static void main(String ar[])
{
CChild obj=new CChild(); System.out.println(obj.c); obj.show(); System.out.println(obj.b); obj.dis(); System.out.println(obj.a); obj.display();
}
}
3. Hierarichal Inheritance: Derivation of several classes from a Single Super Class is called “Hierarchical Inheritance”.
class A
{
int a=10;
void Adisplay()
{
System.out.println("CLASS A");
}
}
class B extends A
{
int b=20;
void Bdisplay()
{
System.out.println("CLASS B");
}
}
class C extends A
{
int c=30;
void Cdisplay()
{
System.out.println("CLASS C");
}
}
class Hierarchy
{
public static void main(String a[])
{
C obj3=new C();
System.out.println("obj1.a="+obj3.a); obj3.Adisplay(); System.out.println("obj2.b="+obj3.b); obj3.Bdisplay(); System.out.println("obj3.c="+obj3.c); obj3.Cdisplay();
}
}
SUPER KEYWORD
Definition :The super keyword in Java is a reference variable which is used to refer immediate parent class object.
/* SUPER KEYWORD */�
class S
{
final int i=10;
void display()
{
i=i+1;
System.out.println(i);
}
}
class C extends S
{
void display()
{
int i=20; System.out.println("Child"); System.out.println(super.i); super.display();
}
}
class SKeyword
{
public static void main(String ar[])
{
S obj1=new S();
Cobj2=newC(); obj1.display();
}
}