Sunday, 22 November 2015

INHERITANCE


5. INHERITANCE

Acquiring the properties from one class to another class is called inheritance

                                    (or)

Producing a new class from already existing class is called inheritance

Reusability of  code is main advantage of inheritance

In java Inheritance is achieved by using extends keyword .

Properties with an access specifier – private can’t be inherited.

Example:

class    Parent{

                        String Pname;

                        String FamilyName;

}

class child extends Parent{

String childName;

int childAge;

void printMyName(){

System.out.println(“My name is”+ childName+ “ “+FamilyName);

}

 

Example 2:

package javatuts;

 

 

class person {

   String name;

   String addr;

   int age;

   void setdetails(String name,String addr,int age){

       this.name=name;

       this.addr=addr;

       this.age=age;

   }

   void getdetails(){

       System.out.println("name:"+name);

       System.out.println("address:"+addr);

       System.out.println("age:"+age);

   }

}

package javatuts;

 

 

class employ extends person{

    int id;

    String companyName;

    String companyAddress;

    employ(int id,String name,String addr,int age,String companyName,String companyAddress){

        this.id=id;

        setdetails(name,addr,age);

        this.companyName=companyName;

        this.companyAddress=companyAddress;

    }

    void getEdetails(){

        System.out.println("employ id"+id);

        getdetails();

        System.out.println("companyName:"+companyName);

        System.out.println("company address:"+companyAddress);

    }

}

public class inherit {

    public static void main(String[] args)

    {

        employ e1=new employ(101,"raees","12-madhnagar",29,"softsolutions","20-hyu");

        e1.getEdetails();

       

    }}

Output:

employ id101

name:raees

address:12-madhnagar

age:29

companyName:softsolutions

company address:20-hyu

No comments:

Post a Comment