Showing posts with label Inheritance. Show all posts
Showing posts with label Inheritance. Show all posts

Friday, 1 November 2013

Hierarchical Inheritance

In hierarchical  inheritance, one class is extended by many subclasses. It is one-to-many relationship.
 In the following example there are two child classes that inherit the same base class "Hinh" and in the main class, objects of both the child classes are created that call the respective functions. Both the child functions call the functions defined in their body and the function of the base class.

Program for Hierarchical Inheritance

import java.io.*;
class Hinh
{
void fun_hinh()
{
System.out.println("Function of hinh class");
}
}

class Childone extends Hinh
{
void fun_childone()
{
System.out.println("Function of childone class");
}
}

class Childtwo extends Hinh
{
void fun_childtwo()
{
System.out.println("Function of childtwo class");
}
}

public class Main_class
{
public static void main(String arg[])
{
Childone ch1=new Childone();
ch1.fun_hinh();
ch1.fun_childone();
Childtwo ch2=new Childtwo();
ch2.fun_hinh();
ch2.fun_childtwo();
}
}


Output:


Thursday, 6 June 2013

Multilevel Inheritance

Multilevel inheritance is the form of inheritance in which there is a base class and the derived class. The derived class is itself the base class .Derived class itself acts as the base class of some other derived class.


Following is the code of a multilevel inheritance.The code below has four classes Fclass ,Sclass, Tclass,Mlevel. Fclass is the base class for Sclass, Sclass is the derived lass for Fclass and acts as the base class for Tclass, Tclass is the derived class of Sclass.
Mlevel class creates object of the Tclass and using objects functions f1,f2 and f3 are called.

Program for Multilevel Inheritance

class Fclass
{
void f1()
{
System.out.println("First Class");
}
}

class Sclass extends Fclass
{
void f2()
{
System.out.println("Second Class");
}
}

class Tclass extends Sclass
{
void f3()
{
System.out.println("Class three");
}
}

class Mlevel
{
public static void main(String arg[])
{
Tclass obj=new Tclass();
obj.f1();
obj.f2();
obj.f3();
}
}

Following is the output of the above code for better understanding:


Single level Inhertance

In single level inheritance there is one base class and one child class that inherits the  features of the base class. The child class inherits the child class using the keyword"extends".
Syntax for single level inheritance is:
   class Child_class_name extends Base_class_name

Program for Single Level Inheritance

class My        //Base class
{
void input()
{
System.out.println("Class My");
}
}

class You extends My                       // class You inherits My class
{
void output()
{
System.out.print("Class You");
}
}

class Slevel
{
public static void main(String arg[])
{
You obj=new You();
obj.input();
obj.output();
}
}

full details in json
Proudly Powered by Blogger.
back to top