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

Saturday, November 6, 2021

Java Inheritance Program On Spare Parts

 This is a program on inheritance which deals with spare parts. This program shows alarm while stock is below certain specified numbers.

import java.io.*;
 class Parts
 {
     String parts1, parts2, parts3;     
     Parts(String parts1, String parts2, String parts3)
     {
        this.parts1=parts1;
        this.parts2=parts2;
        this.parts3=parts3;
    }             
        
    }
  
    class PartsRates extends Parts
    {
       double rate1, rate2, rate3;
       int stock1, stock2, stock3;
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       PartsRates(String parts1, String parts2, String parts3,double rate1, double rate2, double rate3 )
       {
        super(parts1, parts2, parts3);
        this.rate1=rate1;
        this.rate2=rate2;
        this.rate3=rate3;
    }
    protected void takeStock() throws IOException
    {         
            boolean bool=true;
            bool=true;
            while(bool)
            {
                try
                {
                    System.out.print("\nNumber of Pcs of Parts1: ");
                    stock1=Integer.parseInt(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Stock Properly...");
        }
    }
    bool=true;
    while(bool)
            {
                try
                {
                    System.out.print("\nNumber of Pcs of Parts2: ");
                    stock2=Integer.parseInt(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Stock Properly...");
        }
    }
    bool=true;
    while(bool)
            {
                try
                {
                    System.out.print("\nNumber of Pcs of Parts3: ");
                    stock3=Integer.parseInt(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Stock Properly...");
        }
    }
}
    
    
    protected void showRecords()
    {
        
            System.out.println("Parts Number 1: "+parts1+ " Rate: " + rate1+ " No of Pcs: " + stock1);
            System.out.println("Parts Number 2: "+parts2+ " Rate: " + rate2+ " No of Pcs: " + stock2);
            System.out.println("Parts Number 3: "+parts3+ " Rate: " + rate3+ " No of Pcs: " + stock3);
        }   
    
    protected void showAlarmingStock()
    {
       System.out.println("\nParts with Stock less than equal to 10 are as follows");
       if(stock1<10)
       System.out.println("Parts Number 1: "+parts1+ " Rate: " + rate1+ " No of Pcs: " + stock1); 
       if(stock2<10)
       System.out.println("Parts Number 2: "+parts2+ " Rate: " + rate2+ " No of Pcs: " + stock2); 
       if(stock3<10)
       System.out.println("Parts Number 3: "+parts3+ " Rate: " + rate3+ " No of Pcs: " + stock3); 
    }
    
}
class PartsDetails
{
    
        public static void main(String args[])throws IOException
        {
            int choice=1;
            boolean bool=true;
            String parts1, parts2, parts3;
            double rate1=0, rate2=0, rate3=0;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("\nEnter Name of Parts Number 1: ");
            parts1=br.readLine();
            bool=true;
    while(bool)
            {
                try
                {
                    System.out.print("\nRate / Pc of Parts1: ");
                    rate1=Double.parseDouble(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Properly...");
        }
    }
       System.out.print("\nEnter Name of Parts Number 2: ");
            parts2=br.readLine();
            bool=true;
    while(bool)
            {
                try
                {
                    System.out.print("\nRate / Pc of Parts2: ");
                    rate2=Double.parseDouble(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Properly...");
        }
    }
    
    System.out.print("\nEnter Name of Parts Number 3: ");
            parts3=br.readLine();
            bool=true;
    while(bool)
            {
                try
                {
                    System.out.print("\nRate / Pc of Parts3: ");
                    rate3=Double.parseDouble(br.readLine());
                    bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Properly...");
        }
    }
            PartsRates ob=new PartsRates(parts1,parts2,parts3,rate1,rate2,rate3);
            ob.takeStock();
             while(choice!=0)
            {
                System.out.println("Enter 1 to view Full Records, 2 to view Records where stock is less and 0 exit: ");
                choice=Integer.parseInt(br.readLine());
                switch(choice)
                {
                     case 1:
                     ob.showRecords();
                     break;
                     case 2:
                     ob.showAlarmingStock();
                     break;
                     case 0:
                     System.out.print("\nEnd of Program.");
                     break;
                     default:
                     System.out.print("\nWrong Choice.");
                    }
                }
            }
        }
                
            

            Sample Input Output

            
            Enter Name of Parts Number 1: Parts1
Rate / Pc of Parts1: 100
Enter Name of Parts Number 2: Parts2
Rate / Pc of Parts2: www
Enter Properly...
Rate / Pc of Parts2: 200
Enter Name of Parts Number 3: Parts3
Rate / Pc of Parts3: 230
Number of Pcs of Parts1: 12
Number of Pcs of Parts2: 13
Number of Pcs of Parts3: 9

Enter 1 to view Full Records, 2 to view Records where stock is less and 0 exit: 
1

Parts Number 1: Parts1 Rate: 100.0 No of Pcs: 12
Parts Number 2: Parts2 Rate: 200.0 No of Pcs: 13
Parts Number 3: Parts3 Rate: 230.0 No of Pcs: 9

Enter 1 to view Full Records, 2 to view Records where stock is less and 0 exit: 
2

Parts with Stock less than equal to 10 are as follows
Parts Number 3: Parts3 Rate: 230.0 No of Pcs: 9
Enter 1 to view Full Records, 2 to view Records where stock is less and 0 exit: 
0

                     
               

Java Program On Inheritance - Employee And Details

This is a program on inheritance where personal records of Employees will be managed in super class and the sub class will deal with professional records. Authentication while entering values are done.

import java.io.*;
 class EmployeePersonal
 {
     String name[], address[], contact[], qualification[];
     int age[],n;
     BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
     EmployeePersonal(int n1)
     {
        n=n1;
        name=new String[n]; 
        address=new String[n];
        contact=new String[n];
        qualification=new String[n];
        age=new int[n];
    }
    protected void takePersonalDetails(int i) throws IOException
    {
        
            boolean bool=true;
            System.out.print("\nName: ");
            name[i]=br.readLine();
            System.out.print("\nAddress: ");
            address[i]=br.readLine();
            while(bool)
            {
                try
                {
            System.out.print("\nAge: ");
            age[i]=Integer.parseInt(br.readLine());
            bool=false;
        }catch(Exception e)
        {
            System.out.println("\nEnter Age Properly...");
        }
    }
    bool=true;
    while(bool)
    {
            System.out.print("\nContact Number: ");
            contact[i]=br.readLine();
            if(contact[i].length()>=10 && contact[i].length()<=14)
            bool=false;
            else
            System.out.println("\nContact Number Should Be XXXXXXXXXX / +91 XXXXXXXXXX ");
        }       
            System.out.print("\nQualification: ");
            qualification[i]=br.readLine();
       
    }
    protected boolean authentication(String s)
    {
        int day=0, month=0, year=0;
        boolean bool=true;
        int i,len,counter=0,leap;
        len=s.length();
        for(i=0;i<len;i++)
        { 
            if(s.charAt(i)=='/')
            counter++;
        }
        if(counter!=2)
        bool=false;
        else if(counter==2)
        {            
        i=s.indexOf('/');
        day=Integer.parseInt(s.substring(0,i));
        s=s.substring(i+1);
        i=s.indexOf('/');
        month=Integer.parseInt(s.substring(0,i));
        s=s.substring(i+1);
        year=Integer.parseInt(s);         
        if(year%100==0 && year%400==0)
        leap=1;
        else if(year%100!=0 && year%4==0)
        leap=1;
        else
        leap=0;
        if((month==4 || month==6 || month==9 || month==1) && day>30)
        bool=false;
        else if((month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) && day>31)
        bool=false;
        else if (leap==1 && month==2 && day>29)
        bool=false;
        else if (leap==0 && month==2 && day>28)
        bool=false;
        else if(month>12)
        bool=false;
    }
     
    
        return bool;
    }             
        
    }
  
    class EmployeeProfession extends EmployeePersonal
    {
       String department[], designation[], joining[]; 
       double basic[];
       EmployeeProfession(int n1)
       {
        super(n1);
        department=new String[n1]; 
        designation=new String[n1];
        joining=new String[n1];
        basic=new double[n1];
    }
    protected void takeProfessionalDetails(int i) throws IOException
    {
         boolean bool=true;
         takePersonalDetails(i);
            System.out.print("\nDepartment: ");
            department[i]=br.readLine();
            System.out.print("\nDesignation: ");
            designation[i]=br.readLine();
            while(bool)
            {
            System.out.print("\nDate of joining (dd/mm/yyyy): ");
            joining[i]=br.readLine();
            if(authentication(joining[i]))
            bool=false;
            }
        bool=true;
            while(bool)
            {
                try
                {
            System.out.print("\nBasic Salary: ");
            basic[i]=Double.parseDouble(br.readLine());
            bool=false;
        }catch(Exception e)
        {
              System.out.println("\nEnter Basic Salary Properly...");
        }
        }
    }
    
    protected void showCompleteRecords()
    {
        System.out.println("Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary");;
        for(int i=0;i<n;i++)
        {
            System.out.println(name[i]+ " " + address[i]+ " " + age[i]+ " " + contact[i]+ " "+ qualification[i]+ " "+department[i]+ " "+designation[i]+ " "+ joining[i]+ " "+ basic[i]);
        }   
    }
    protected void showProfessionalRecords()
    {
        System.out.println("Name           Department  Designation Date of Joining   Basic Salary");;
        for(int i=0;i<n;i++)
        {
            System.out.println(name[i]+ " " + department[i]+ " "+designation[i]+ " "+ joining[i]+ " "+ basic[i]);
        }   
    }
    
    protected void showDepartmentWiseRecords() throws IOException
    {
       String dept;
       int x=0;
       System.out.print("\nEnter Department: ");
       dept=br.readLine();
       System.out.println("Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary");;
        for(int i=0;i<n;i++)
        {
           if(dept.equalsIgnoreCase(department[i]))
           {
               System.out.println(name[i]+ " " + address[i]+ " " + age[i]+ " " + contact[i]+ " "+ qualification[i]+ " "+department[i]+ " "+designation[i]+ " "+ joining[i]+ " "+ basic[i]);
               x=1;
            }
        }
        if(x==0)
        System.out.println("\nNot A Single Employee In This Department ");
    }
    protected void showBasicWiseRecords() throws IOException
    {
       double basic_sal;
       int x=0;
       System.out.print("\nEnter Basic Salary: ");
       basic_sal=Double.parseDouble(br.readLine());
       System.out.println("Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary");;
        for(int i=0;i<n;i++)
        {
           if(basic_sal>=basic[i])
           {
               System.out.println(name[i]+ " " + address[i]+ " " + age[i]+ " " + contact[i]+ " "+ qualification[i]+ " "+department[i]+ " "+designation[i]+ " "+ joining[i]+ " "+ basic[i]);
               x=1;
            }
        }
        if(x==0)
        System.out.println("\nNot A Single Employee Found ");
    }
}
class Employee
{
    
        public static void main(String args[])throws IOException
        {
            int choice=1,n,i;
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("\nHow Many Employees: ");
            n=Integer.parseInt(br.readLine());
            EmployeeProfession ob=new EmployeeProfession (n);
            for(i=0;i<n;i++)
            ob.takeProfessionalDetails(i);
            while(choice!=0)
            {
                System.out.println("Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: ");
                choice=Integer.parseInt(br.readLine());
                switch(choice)
                {
                     case 1:
                     ob.showCompleteRecords();
                     break;
                     case 2:
                     ob.showProfessionalRecords();
                     break;
                     case 3:
                     ob.showDepartmentWiseRecords();
                     break;
                     case 4:
                     ob.showBasicWiseRecords();
                     break;
                     case 0:
                     System.out.print("\nEnd of Program.");
                     break;
                     default:
                     System.out.print("\nWrong Choice.");
                    }
                }
            }
        }
                

       Sample Input Output


How Many Employees: 2
Name: Abinash
Address: Burdwan
Age: 23
Contact Number: 98765445
Contact Number Should Be XXXXXXXXXX / +91 XXXXXXXXXX 
Contact Number: 9874009876
Qualification: B.Tech
Department: Spinning
Designation: Spg. Master
Date of joining (dd/mm/yyyy): 11/22/2000
11:22:2000
Date of joining (dd/mm/yyyy): 11/11/2020
11:11:2020
Basic Salary: 2345

Name: Amal
Address: Kolkata
Age: 26
Contact Number: 9876009834
Qualification: B.E
Department: Weaving
Designation: Wvg. Manager
Date of joining (dd/mm/yyyy): 11/11/2000
11:11:2000
Basic Salary: 5555

Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
1
Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary
Abinash Burdwan 23 9874009876 B.Tech Spinning Spg. Master 11/11/2020 2345.0
Amal Kolkata 26 9876009834 B.E Weaving Wvg. Manager 11/11/2000 5555.0

Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
2

Name           Department  Designation Date of Joining   Basic Salary
Abinash Spinning Spg. Master 11/11/2020 2345.0
Amal Weaving Wvg. Manager 11/11/2000 5555.0

Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
3

Enter Department: Spinning
Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary
Abinash Burdwan 23 9874009876 B.Tech Spinning Spg. Master 11/11/2020 2345.0
Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
2

Name           Department  Designation Date of Joining   Basic Salary
Abinash Spinning Spg. Master 11/11/2020 2345.0
Amal Weaving Wvg. Manager 11/11/2000 5555.0
Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
4

Enter Basic Salary: 4444
Name           Address       Age  Contact No  Qualification   Department  Designation Date of Joining   Basic Salary
Abinash Burdwan 23 9874009876 B.Tech Spinning Spg. Master 11/11/2020 2345.0
Enter 1 to view Full Records, 2 to view only Professional Records, 3 to view Department wise record, 4 to view Basic Salary wise Records and 0 to exit: 
0

Tuesday, September 6, 2011

Multiple inheritance in C++ Programming Language


In multiple inheritance in C++ Programs, a derived class inherits a number of classes which are not linked with one another.

Here is an Inheritance in C++ with example


#include< iostream.h >
#include< stdio.h >
#include< conio.h >
class str
{
private:
char name [40],address [40];
public:
void getData1 ()
{
fflush(stdin);
puts("Enter the name: -");
gets(name);
fflush (stdin);
puts("Enter the address: -");
gets(address);
}
void display1 ()
{
cout<< name<< endl;
cout<< "Address: -"<< address<< endl;
}
};
class num
{
private:
int age;
long tel_no;
public:
void getData2 ()
{
cout<< "Enter the age: -";
cin >>age;
cout<< "Enter the Telephone Number: -";
cin >>tel_no;
}
void display2 ()
{
cout<< "Age: -"<< age<< endl;
cout<< "Telephone Number: -"<< tel_no<< endl;
}
};
class final:public str,public num
{
private:
char gender [10];
public:
void getData3 ()
{
cout<< "Enter the gender(Mr./Miss.): -";
cin >>gender;
}
void display3 ()
{
cout<< gender<< " ";
}
};
void main ()
{
clrscr ();
final ob1,ob2;
cout<< "For the 1st object:-"<< endl;
ob1.getData1 ();
ob1.getData2 ();
ob1.getData3 ();
cout<< "For the 2nd object:-"<< endl;
ob2.getData1 ();
ob2.getData2 ();
ob2.getData3 ();
clrscr ();
cout<< "1st object values are: -"<< endl;
ob1.display3 ();
ob1.display1 ();
ob1.display2 ();
cout<< endl<< "Press any key to continue.........";
getch ();
clrscr ();
cout<< endl<< "2nd object values are: -"<< endl;
ob2.display3 ();
ob2.display1 ();
ob2.display2 ();
getch ();
}

In the above C++ program on inheritance, the class 'str' contains two private data members - char name [40],address [40]; and two public function members void getData1 () and void display1 ().

There is another class in the above program 'num'. This class also contains two private data members int age;long tel_no; and two public function members - void getData2 () and void display2 ().

The third class is 'final' which inherits both the above classes. This is an example of multiple inheritance where a derived class can have a number of different classes.

As the data members are declared private in str and num, they can not be accessed in class final. So these members are accessed through the functions of the class itself. To access the data members from the derived class the following modification is needed.

After modification Inheritance in C++ with example


#include< iostream.h >
#include< stdio.h >
#include< conio.h >
class str
{
protected:
char name [40],address [40];
public:
};
class num
{
protected:
int age;
long tel_no;
};
class final:public str,public num
{
private:
char gender [10];
public:
void getData ()
{
fflush(stdin);
cout<< "Enter the gender(Mr./Miss.): -";
cin >>gender;
puts("Enter the name: -");
gets(name);
fflush (stdin);
puts("Enter the address: -");
gets(address);
cout<< "Enter the age: -";
cin >>age;
cout<< "Enter the Telephone Number: -";
cin >>tel_no;
}
void display ()
{
cout<< gender<< " ";
cout<< name<< endl;
cout<< "Address: -"<< address<< endl;
cout<< "Age: -"<< age<< endl;
cout<< "Telephone Number: -"<< tel_no<< endl;
}
};
void main ()
{
clrscr ();
final ob1,ob2;
cout<< "For the 1st object:-"<< endl;
ob1.getData ();
cout<< "For the 2nd object:-"<< endl;
ob2.getData ();
clrscr ();
cout<< "1st object values are: -"<< endl;
ob1.display ();
cout<< endl<< "Press any key to continue.........";
getch ();
clrscr ();
cout<< endl<< "2nd object values are: -"<< endl;
ob2.display ();
getch ();
}

Again modifications are done on the above C++ program. The data members are declared private in the base classes and all the three classes have their own void getData () and void display () functions. The derived class final inherits the two classes by using the statement class final:private str,private num . So the members of  str and num are not accessible outside the respective class. So, to enter values we will call the getData () function of the derived class final and from within the function the functions of the base classes will be called.

#include< iostream.h >
#include< stdio.h >
#include< conio.h >
class str
{
private:
char name [40],address [40];
public:
void getData ()
{
fflush(stdin);
puts("Enter the name: -");
gets(name);
fflush (stdin);
puts("Enter the address: -");
gets(address);
}
void display ()
{
cout<< name<< endl;
cout<< "Address: -"<< address<< endl;
}
};
class num
{
private:
int age;
long tel_no;
public:
void getData ()
{
cout<< "Enter the age: -";
cin >>age;
cout<< "Enter the Telephone Number: -";
cin >>tel_no;
}
void display ()
{
cout<< "Age: -"<< age<< endl;
cout<< "Telephone Number: -"<< tel_no<< endl;
}
};
class final:private str,private num
{
private:
char gender [10];
public:
void getData ()
{
cout<< "Enter the gender(Mr./Miss.): -";
cin >>gender;
str::getData ();
num::getData ();
}
void display ()
{
cout<< gender<< " ";
str::display ();
num::display ();
}
};
void main ()
{
clrscr ();
final ob1,ob2;
cout<< "For the 1st object:-"<< endl;
ob1.getData ();
cout<< "For the 2nd object:-"<< endl;
ob2.getData ();
clrscr ();
cout<< "1st object values are: -"<< endl;
ob1.display ();
cout<< endl<< "Press any key to continue.........";
getch ();
clrscr ();
cout<< endl<< "2nd object values are: -"<< endl;
ob2.display ();
getch ();
}

#include< iostream.h >
#include< conio.h >
class A
{
public:
void show()
{
cout<< "\nInside class A.";
}
};
class B
{
public:
void show()
{
cout<< "\nInside class B.";
}
};
class C:public A,public B
{
};
void main()
{
C ob;
ob.show()//error generated in this statement
ob.A::show();
ob.B::show();
getch();
}

In the above C++ program both the classes A and B have show () function. Object of derived class  C can access both but not directly.

When we inherit a base class privately , the derived class has all the data and functions of the base class, but the functionality is hidden, means the members of the base class can be accessed in the derived class but not outside it. When we inherits privately all the public and protected members of the base class becomes private members of the derived class. To demonstrate this feature the same program is modified again.

Another program on Inheritance in C++ with example


#include< iostream.h >
#include< stdio.h >
#include< conio.h >
class str
{
private:
char name [40],address [40];
public:
void getData ()
{
fflush(stdin);
puts("Enter the name: -");
gets(name);
fflush (stdin);
puts("Enter the address: -");
gets(address);
}
void display ()
{
cout<< name<< endl;
cout<< "Address: -"<< address<< endl;
}
};
class num
{
protected:
/* modification is done here. Data members are declared as protected*/
int age;
long tel_no;
public:
void getData ()
{
cout<< "Enter the Telephone Number: -";
cin >>tel_no;
}
void display ()
{
cout<< "Age: -"<< age<< endl;
cout<< "Telephone Number: -"<< tel_no<< endl;
}
};
class final:private str,private num
{
private:
char gender [10];
public:
void getData ()
{
cout<< "Enter the gender(Mr./Miss.): -";
cin >>gender;
cout<< "Enter the age: -";
cin >>num::age;
/* now the protected member of the base class num is accessed hare. As num is derived privately , the derived class can not access it’s protected member directly*/
str::getData ();
num::getData ();
}
void display ()
{
cout<< gender<< " ";
str::display ();
num::display ();
}
};
void main ()
{
clrscr ();
final ob1,ob2;
cout<< "For the 1st object:-"<< endl;
ob1.getData ();
cout<< "For the 2nd object:-"<< endl;
ob2.getData ();
clrscr ();
cout<< "1st object values are: -"<< endl;
ob1.display ();
cout<< endl<< "Press any key to continue.........";
getch ();
clrscr ();
cout<< endl<< "2nd object values are: -"<< endl;
ob2.display ();
getch ();
}

Monday, September 5, 2011

Inheritance in C++ with example


Inheritance is the process by which the object of a derived or sub class can acquire the properties of an existing class. Suppose we want to change the above program so that it’s object will contain another long type variable to store the phone number. It is not always possible to modify the class. So we inherits the properties of the object of the above class (here person) to another class Phone and add new features in the class Phone. Ultimately we will create objects of class Phone.

Here is the sample C++ program on Inheritance.

#include< iostream.h>
#include< stdio.h>
#include< conio.h>
class person
{
protected:
char name [40];
public:
void setName ()
{
puts ("Enter Name: -");
gets (name);
}
};
class Phone: public person /* class Phone is a derived class of person*/
{
private:
long phone_no;
public:
void getPhone ()
{
cout<< "Enter the Phone Number: -";
cin >>phone_no;
}
void display ()
{
cout<< "\nName is: -"<< name;
cout<< "\t"<< phone_no;
}
};
void main ()
{
clrscr ();
Phone p;
Phone *ptr [10];
int n=0;
char choice;
do
{
ptr [n]=new Phone;
ptr [n]->setName ();
ptr [n]->getPhone ();
n++;
fflush (stdin);
cout<< "Another (y/n): -";
cin >>choice;
} while (choice=='y');
for (int i=0;i< n; i++)
{
ptr [i]->display ();
}
getch ();
}

Friday, September 2, 2011

Programs on multilevel inheritance in Java


We know that multilevel inheritance means where one class inherits the properties of the object of any pre defined class. The class which inherits is called sub class or some times derived class although the word derived is related to C++ programming language. The class which is being inherited is called super class. Sometimes it is referred as base class. Normally the word base class associated with C++ programming language.

Inheritance means acquiring the properties of any predefined class by a class and it may continue for several layers. For example, suppose ‘A’ is a defined class and class ‘B’ inherits class ‘A’. Again class ‘C’ may inherits class ‘B’ and the process may continue.

Let’s see what is the meaning of ‘acquiring the properties’.

Let’s start with a program.

import java.io.*;
class Record
{
String name[]=new String[10];
String add[]=new String[10];
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 public void take()throws Exception
 {
 for(i=0;i< 10;i++)
 {
  System.out.println("Enter name:");
  name[i]=br.readLine();
 System.out.println("Enter address:");
  add[i]=br.readLine();
}
 }
 public void display()
 {
      System.out.println("Name           Address");
      for(i=0;i< 10;i++)
      {
           System.out.println(name[i]+ "  "+add[i]);
        }
    }
   
}
class FinalRecord extends Record
{
String temp;
int i,j;
  public void sort()
  {
      for(i=0;i< 9;i++)
      {
           for(j=i+1;j< 10;j++)
           {
               if(name[i].compareTo(name[j])>0)
               {
                   temp=name[i];
                   name[i]=name[j];
                   name[j]=temp;
                   temp=add[i];
                   add[i]=add[j];
                   add[j]=temp;
                }
            }
        }
    }


  public static void main(String args[]) throws Exception
  {
 FinalRecord ob=new FinalRecord();
  ob.take();
  System.out.println("Entered records are\n");
  ob.display();
  ob.sort();
  System.out.println("Records in sorted order\n");
  ob.display();
   }
   }
  
In the above program, class Record contains two String class arrays to store name and address and two functions. One function will store the records (name and address) and the other function will display the records.
If we create object of the class ‘Record’ then with the object we can only perform the above jobs as defined within function body.

Now, our sub class FinalRecord inherits the class Record. It means that the objects of class FinalRecord can use all the members defined in the above class ‘Record’ and also the members defined within its body. Here one point to be remembered that the sub class of this above program can access all the members of its super class as the members in the super class are not of ‘private’ access specifier.
Sub class ‘FinalRecord’ has defined another function to sort the names in alphabetical order and accordingly the addresses will be arranged.

Inside the main() function, object of sub class ‘FinalRecord’ is created and all the members ( data member and function member) of the super class plus the function ‘sort()’ which is exclusively defined in the sub class present in the object of ‘FinalRecord’ class.

Subscribe via email

Enter your email address:

Delivered by FeedBurner