Friday, April 28, 2017

Relationship In Java (Inheritance and Aggregation)

Relations in Java

Inheritance (IS-A Relation )

The process where one class derived from other classes, there by inherits the fields and methods of other classes. This process in java is called Inheritance.  It is also called IS-A relation between the classes.

A class that is derived from another class is called Sub Class or child Class or derived Class and the Class from which class is derived is called Super Class or parent Class or base class.


Types of Inheritance:

  1. Single inheritance:  if a class derived from another class only it is called single inheritance.E.g. suppose class B derived from class A only

  2.  Multiple inheritance: - if a class is derived from more than one class than this type of inheritance is called multiple inheritance.E.g. Suppose Class B derived from class A , Class C and Class D .




  3. Multi Level Inheritance:  if a class is derived from another class and its super class is also derived from some other class this type of inheritance is called multi level inheritance.E.g. Class B derived from Class A and Class A derived from Class X. it mean class B is not the direct child of class X


  4. Cyclic inheritance: if a Class derived from another class and its super class derived from its child. This type of inheritance is called cyclic inheritance.
    E.g Class B derived from Class A and Class A Derived From Class B.


    If a class derived its self, then it is also called Cyclic Inheritance. E.g. Class A derived from Class A

Inheritance in Java

In java by using extends keyword we can implement inheritance or established IS-A relation between the Classes. Java don’t support multiple and cyclic inheritance.
The main advantages of IS-A relation is reusability of a code.

A sub class inherits the entire member (field, methods and nested inner classes) from its super class except private member. Constructors are not the members, so they are not inherited by sub class But Super class constructor must be invoked from subclass for initializing the super class data members.
Whatever the field and methods parent class have by default available to child class and we can call access them by using child reference BUT whatever the methods and field child Class have not available to the parent class and by using parent reference we can’t access child specified members.

Parent reference can be used to hold the child class object but by using this reference we can only access parent specified member from child object. And we can’t access child specified member by using parent reference even though it refer child object.
Child class reference can’t hold parent class object.
Private member can’t be access by the child class but private field or variables can be access indirectly by child class using methods and inner classes declared in parent class.

The most common method which is applicable for all child class we have to define it in parent class and the specific method which are applicable for particular child only we define those method in child class.
The object class act as root class for all java classes in java API.
Every class directly or indirectly a child of Object class i.e. Object class is the only class in java which don’t have any parent class.

If our class extends some other Class than our class is not the direct child of Object class but it is indirect child of Object class. Hence, if our class doesn’t extends any class than only our class is a Direct Child of Object Class.
The most common methods which are applicable for all java Object is define inside a Object Class of java which is present inside java.lang package.

Reason for why java do not support multiple inheritance at class level:- There is chance  of ambiguity problem. Suppose both super class contain one method with same name and child invoke the method than which super class method is invoked there is ambiguity problem therefore java doesn’t support multiple inheritance at class level.

Disadvantage of Inheritance:

  1. Sub class object can get the functionality only once. We can’t inherit a data member twice.
  2. Sub class Object gets All functionality of super Class even though it required or not.
  3. There should be tight coupling between the classes mean if we make change in one class effect the other class.
  4. One class can extend at most one class only. If a class need functionality of two different classes than it’s not possible to extends both class.


Association (Has-A relation)

In Object oriented Programming, One Object is related two other object to use the functionality and services provided by the other object. This relation between two objects is called Association or Has-A relation.
The object which using the functionality of other object is called Container Object and the object whose functionality is used are called Contained Object.

Association is of two types:

  1. Aggregation: if there is chance of existing contained object without the existence of container object i.e.  if container object is weakly associated with contained object that this type of association is called aggregation.
    E.g. relation between University and professor Object
  2. Composition:  without existing container object if there is no chance of existing contained object than this association is called composition. Here the container and contained object are strongly associated to each other.
    E.g. Relation between University and its department Objects. 
Note: In Composition Container Object directly holds the contained object where as in aggregation Container Object Only Holds the reference of contained object class.


        


Data Hiding,Abstraction and Encapsulation

Data Hiding

Outside person can’t access our internal data directly or internal data variable can’t be access directly from outside. This feature of oops is called Data hiding. We can access these variables through methods.
The main advantage of this feature is to provide Security. 

We can achieve this feature by declaring our variable as private variable.

Abstraction

Hiding the internal implementation and just Highlighting the set of Service is called Abstraction.
We can achieve the Abstraction by using Abstract class or interface in our program.
The main advantage of these feature are:
  1.      We can achieve the security to next level.
  2.       Enhancement of the system becomes easy without affecting the end user.
  3.       It improves the maintainability of the system.
  4.       It provides more flexibility to end user to use system easily.

Encapsulation

The process of binding data members (variables) and methods into a single unit is called Encapsulation.
Technically if any unit follows data hiding and abstraction then we say this unit follows encapsulation and it is encapsulated.

Encapsulation = Data Hiding + Abstraction

Advantage of encapsulation is similar as Abstraction.
The Disadvantage of encapsulation is it increases the length of code and execution time will increase.

Tightly encapsulated


A class is said to be tightly encapsulated if and only if  each variable of the class is declared to be private whether class contain corresponding setter and getter or not and  whether these methods declare public or not.
                It means for tightly encapsulation all variable must be private only.
If the parent class is not tightly encapsulated then its child class also not tightly encapsulated even if it declare its all variable as private.

Anonymous Array and Array Assignment

Anonymous Array

Array without name is called Anonymous array.
Some time we declare an array without name such type of nameless array is called anonymous array.
The main purpose of this array is just for instant used (one time use).
Example:- suppose  a condition a method taking array as parameter than just to pass the argument as array we create an array.

class Test
{                             
     public static void main(String[] args){
        System.out.println("Sum="+sum(new int[]{10,20,30,40}));                
                }
     public static int sum(int[] numbers){
        int total=0;
        for(int no:numbers){
             total=total+no;
                  }
             return total;
                }
               
}

We can create anonymous array as follow:

new int[]{10,20,30,40}

While creating anonymous array we can’t specify the size of array if  we try to specify than we will get compile time error .
new int[4]{10,20,30,40}   àC.E
new int[]{10,20,30,40}  Correct

we can create multi-dimensional anonymous array also.

new  int [][]{{10,20},{5,8,15}}

Based on our requirement we also provide name to the anonymous array but it is no longer be an anonymous array.

Int[][]  x = new  int [][]{{10,20},{5,8,15}};

Array element assignment

Here we learn which types of element are allowed to assign in which type of array.

Case 1: In the case of Primitive type array as array element we can be assign any type of element which can implicitly promoted to declared type.

Example
                int [] x = new int[6];
                x[0]=10;
                x[1]='a';
                byte b=30;
                x[2]=b;
                char c='d';
                x[3]=c;
                short s=56;

                x[4]=s;
                 long f=10L;

                 x[5]=f; C.E: possible loss of precision 

Case 2: In case of object type array as array element we can assign or provide either declared type or its child type.

Example 1
                Object [] o = new Object [10];
                o [0]=new Thread();
                o[1]= new String(“hello”);
                o[2]= new Integer(10);

Example 2
                Number [] o = new Number [10];
        o[0]= new Integer(10);
        o[1]= new Double(10.45);
        o[2]= new String(“hello”);C.E: incompatible type

Case3: In case of Abstract class type array as array element we can provide only its child type object.

Case 4: In case of interface type array as array element we assign its implemented class object only.


Example
                Runnable [] r = new Runnable [10];
                r [0]=new Thread();
                r[1]= new String(“hello”);
à C.E : incompatible type

Array Type
Allowed Element Type
Primitive Type
Any type which implicitly promoted to declared type.
Object Type or Class Type
Either declared type object or its child class objects.
Abstract Class Type
Only its child class objects.
Interface Type
Only its implementation class objects.


Array Variable Assignments

Case 1: Element level promotion not allowed to array level.

Example:

char element can Promoted to int type But char Type array (char[]) not promoted to int type array(int[]).

char c=’a’;
int x=c;
char[] c={‘a’,’b’,’c’};
int[] y={1,2,3};
int[] x=y; 
int[] z=c;à C.E : incompatible type 
                                             required: int[]                                              found: char[]


*But in case of Object Type Arrays Child class Array can be promoted to parent Class Type array.

Integer[] y={1,2,3};
Number[] n=y;
String[] s ={“aa”,”ab”,”bb”};
Object[] o=s;

Case 2: whenever we are assigned one array to other array internally the elements of array would not copied to the other array just reference variable will be re-assigned.


Example

int [] a={10,20,30,40};
int [] b={50,60};








Case 3: whenever we assigned on array to another than dimension must be same.

Example

If we want to assign one dimension int [] we should provide one dimensional  array only. If  we provide other dimension than get compile time error.
int[] x={10,20,30};

Array Creation and Initialization

Array Creation.

Every array in java is an object only, hence we can create array by using new operator.

Int []  x= new int[4];

Every array type corresponding classes are available and these classes  are part of java Language But not available for Programmer label.
To know the class of array use getClass() and getName() method on array reference variable.

System.out.Println(x.getClass().getName());


List of Corresponding classes of Array

Array Type
Corresponding Classes
int[]
[I
int[][]
[[I
int[][][]
[[[I
byte[]
[B
short[]
[S
long[]
[L
boolean[]
[Z
char[]
[C
float[]
[F
double[]
[D

1)At the time of array creation compulsory we must specify the size of the array otherwise we will get compile Time Error.

                                 int [] x= new int [4];
2  2) It legal to have the size of array as zero (0) in java.

                                int [] x = new int[0];
     
3)we try to specify the array size as some negative int value than we will get Run Time Exception Saying “negative Array Size Exception”.

                                int[] x = new int[-4];
          Run-Time.Error : java.lang.NegativeArraySizeException

 4) To specify the array size allowed data types are (byte, short, int and char). If we try to specify the other data type we will get compile type error.
                                Ex-1:-
                int[] x = new int[a];

           Ex-2:-

byte b = 3;
int[]y= new int[b];

     5)Maximum allowed Size of the array in java is 2147483648. Because array Class construction takes int data value and max value for int data type is 231-1.

               int[] x= new int[2147483648];

                           C.E : integer number too large

             int[] x= new int[2147483647];

                     Runtime.Error :  java.lang.OutOfMemoryError

Note:-In second case we may also get Run Time Exception saying  “java.lang.OutOfMemoryError: Requested array size exceeds Virtual Machine limit”. Because of memory size allowed to Virtual Machine


2-D Array Creation/Multi-D Array creation




In java 2-D array or multi-dimension array not implemented by using Matrix implementation. SUN people followed array of array approach for multi-Dimensional Array Creation.
The main Advantage of this approach is memory utilization will be improved.

Example 1

int [][] x= new int [2][3]








Note: during creation of multi-dimensional array at least base size we have to specify. Another level  size will be given  latter.

We use when next level array size are vary from each other

Example 2

int [][] x= new [2][];
X[0]= new int [3];
X[1]=new int[2];









Array initialization

Once we create an array every array by default initialized with the default value , if we are not satisfied with default value than we can override this value with our customized value.

int[] x= new int[6];
X[0]=10;
0
10
0
10
0
20
0
130
0
40
0
60
X[1]=10;
X[2]=20;
X[3]=130;
X[4]=40;
X[5]=60;

X[6]=50  R.T.Error :  java.lang.ArrayIndexOutBoundException

X[-6]=50;R.T.Error :  java.lang.ArrayIndexOutBoundException

X[2.5]=230
C.E :  possible loss of precision
required:int
found:double

Note :- if we try to print reference variable of array (suppose x) or when ever we try to print any reference variable by default internally toString() method will be executed . Which is implemented by  default to print the string in the following form:

ClassName @hashcode

Here, hashcode is in hexdecimal memory address representation

Example 1:

int [] x=new int[3];
System.out.println(x);
 System.out.println(x[0]);

Output
[I@xxxx
0

Here , xxxx is hashcode hexadecimal value and 0 is defaut value for int type. 

Example 2:-

int [][] x= new int[2][3];

System.out.println(x);
System.out.println(x[0]);
System.out.println(x[0][1]);

Output
[[I@xxxx
[I@xxxx
0


Example 3:-

int [][] x= new int[2][ ];
System.out.println(x);
System.out.println(x[0]);
System.out.println(x[0][1]);➜Runtime Error


Output
[[I@xxxx
Null
Run time Error: java.lang.NullPointerException

Array declaration, creation, initialization in a single line.


similarly,

char []  vowel = {‘a’,’e’,’i’,’u’,’o’};
String[]  s= {“hello”, “welcome” , “bye”};

We can declare, create and initialize the array in a single line (shortcut representation).
This shortcut is also applicable for multi-dimensional array.

Ex-

int[][] x= { {20,30},{20,10,15}};

Note: - if you want to use this shortcut compulsory you should perform in a single line, if you try to break or divide in multiple line we will get compile time error.

int [] x;
X={10,20,30};    ➜  Compile time error