Friday, 16 January 2015

Inheritance in java


                                                        Inheritance in Java
Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent object.
or
Deriving new classes from existing classes such that the new classes acquire all the features of existing classes is called inheritance.
The syntax of inheritance is:
class subclass extends superclass
super class members are available to sub class. Because,the sub class object contains a copy of super class object.

Advantage of inheritance :
In inheritance,a programmer reuses the superclass code without rewriting it, in creation of subclasses. So,developing the classes becomes very easy.Hence,the programmer's productivity is increased.

class Parent
{
public void p1()
{
    System.out.println("Parent method");
}
}
public class Child extends Parent{
public void c1()
{
    System.out.println("Child method");
}
public static void main(String[] args)
{
    Child c = new Child();
    c.c1();   //method of Child class
    c.p1();   //method of Parent class
}
}

o/p:   child method
     parent method
   



super:- (keyword)

Actually we create sub class object. Because by using this object we can access both sub class members and super class members.

class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle
{
           String modelType;
public void showDetail()
{
    vehicleType = "Car";     //accessing Vehicle class member(super class member)
    modelType = "sports";
    System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
    Car c =new Car();
    c.showDetail();
}
}


But some times,the super class members and sub class members are same names.In that case,by default only subclass members are accessible.In such case,'super' keyword has been invented.
 'super' refers to superclass members from a sub class.

ex:-
1.super can be used to refer to super class variables,as:
    super.variable;

class Parent
{
String name;
}
public class Child extendsParent {
String name;
public void details()
{
    super.name = "Parent";    
//refers to parent class member. super must be 1st one and it is executed
    name = "Child";
    System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
    Child c = new Child();
    c.details();
}
}

o/p: parent and child

2.super can be used to refer to super class methods are:
    super.method();

class Parent
  {
String name;
public void details()
{
  name = "Parent";
    System.out.println(name);
}  
  }
  public class Child extends Parent {
String name;
public void details()
{
    super.details(); //calling Parent class details() method
    name = "Child";
    System.out.println(name);
}
public static void main(String[] args)
{
    Child c = new Child();
    c.details();
}
}

o/p: parent
child

3. super can be used to refer to super class constructor. We need not call the default construtor of the super class,as it is by default available to sub class.
To call the parametereized constructor,we can write:
          super(values);

class Parent
{
String name;

public Parent(String n)
{
    name = n;
}
}
     public class Child extends Parent {
String name;
        public Child(String n1, String n2)
{
   super(n1);    //passing argument to parent class constructor
    this.name = n2;
}
public void details()
{
    System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
    Child cobj = new Child("Parent","Child");
    cobj.details();
}
}

o/p:  parent and child

Types of inheritance:-

There are two types of inheritance:
1.Single inheritance 2.Multiple inheritance.

1.single inheritance:-
Producing sub classes from single superclass is called single inheritance. In this,a single superclass will be there.there can be one or more subclasses.

2.Multiple inheritance:-
Producing sub classes from multiple super classes is called multiple inheritance. In this,there will be more than one superclass and only one sub class.
Only single inheritance is available in JAVA.There is no multiple inheritance in java.
The following are the reasons:
1.Multiple inheritance leads to confusion for the programmer.
ex:- class A has got a member x,and class B also got a member x.When another class C extends both the classes,then there is confusion regarding which copy of x is available in C.

2.Multiple inheritance is available in C++,which is not available in Java.This leads to disappointment in Java programmers.A java programmer wishes to use multiple inheritance in some cases. Fortunately,JavaSoft people have provided interface concept, expecting the programmers to achieve multiple inheritance by using multiple interfaces.
ex:- we can write,
*achieving multiple inhertance by using interfaces is not useful.
class Myclass implements interface1,interface2,....


Why use Inheritance?
1. For Method Overriding (So Runtime Polymorphism).
2. For Code Reusability.

class Employee{  
float salary=8000;  
}  
class Programmer extends Employee{  
int bonus=1000;  
  public static void main(String args[]){  
  Programmer p=new Programmer();  
  System.out.println("Programmer salary is:"+p.salary);  
  System.out.println("Bonus of Programmer is:"+p.bonus);  
}  
}  
Output:Programmer salary is:8000.0
   Bonus of programmer is:1000
here the programmer salary is written in float whereas bonus in integer data type


Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java. For example:


class A
{  
  void msg()
       {
           System.out.println("Hello");}  
    }  
class B
{  
  void msg()
       {
          System.out.println("Good Morning");
         }  
}  
class C extends A,B
    {//suppose if it were  
Public Static void main(String args[])
           {  
              C c=new C();  
               c.msg();//Now which msg() method would be invoked?  
             }  
}  




Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship
Why use Aggregation?
For Code Reusability.

In this example, we have created the reference of Operation class in the Circle class.

class Operation{  
int square(int n){  
 return n*n;  
}  
}  
class Circle{  
Operation op;//aggregation  
double pi=3.14;  
 double area(int radius){  
  op=new Operation();  
  int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
  return pi*rsquare;  
}  
public static void main(String args[]){  
  Circle c=new Circle();  
  double result=c.area(5);  
  System.out.println(result);  
}  
}  
Output:78.5

*********************************************************************
class Author
{
String authorName;
int age;
String place;
Author(String name,int age,String place)
{
 this.authorName=name;
 this.age=age;
 this.place=place;
}
public String getAuthorName()
{
 return authorName;
}
public int getAge()
{
 return age;
}
public String getPlace()
{
 return place;
}
}

class Book
{
String name;
int price;
Author auth;
Book(String n,int p,Author at)
{
 this.name=n;
 this.price=p;
 this.auth=at;
}
public void showDetail()
{
 System.out.println("Book is"+name);
 System.out.println("price "+price);
 System.out.println("Author is "+auth.getAuthorName());
}
}

class Test
{
public static void main(String args[])
{
 Author ath=new Author("Me",22,"India");
 Book b=new Book("Java",550,ath);
 b.showDetail();
}
}
Output
Book is Java.
price is 550.
Author is me.

When to use Aggregation?
Code reuse is also best achieved by aggregation when there is no is-a relationship.

Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.
class A has-a relationship with class B, if code in class A has a reference to an instance of class B.

Can a super class access sub-class object?
Yes. A super class variable can access a sub class object

Q. Can you use both this() and super() in a Constructor?
NO, because both super() and this() must be first statement inside a constructor. Hence we cannot use them together

No comments:

Post a Comment