Wednesday, December 3, 2014

Oops Concepts in java

OOPS Concept in Java:-
Mainly in java 4 OOPS Concept is Available:-
1) Abstraction
2) Encapsulation
3) Inheritance
4) Polymorphism
1)      Abstraction:- abstraction is a process of hiding the unnecessary data and showing the necessary data.


2)      Encapsulation:-  Encapsulation is a process of defining entity with all properties and operation of an object. In programming language terminology an entity is call as class, properties call as variables and operation call as methods.

Example:-
class Test
{

    int a;
    public void setA(int a)
    {
        this.a=a;
        }
    public int getA()
    {
        System.out.println(a);
        return a;
        }
   


Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. Consider this: 
abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }

}

The super class Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hard codes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or in variants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.
============================================================================
You would define a constructor in an abstract class if you are in one of these situations: 
you want to perform some initialization (to fields of the abstract class) before the instantiation of a subclass actually takes place
you have defined final fields in the abstract class but you did not initialize them in the declaration itself; in this case, you MUST have a constructor to initialize these fields. 
Note that:  
you may define more than one constructor (with different arguments)
you can (should?) define all your constructors protected (making them public is pointless anyway).
your subclass constructor(s) can call one constructor of the abstract class; it may even have to call it (if there is no no-arg constructor in the abstract class). 
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).

3) Inheritance:- 
            Inheritance is a process of writing a new class by using existing class functionality.
New class called as sub class, child class or derived class and existing class called as a super class,
base class or parent class. The main goal of inheritance is code re usability.
Example:- 
class Test
{
                int a=10;
                public void m1()
                {
                 System.out.println("Test m1()");
                  }
                }
class Test1 extends Test
{
                //int a=20;
                public void m1()
                {
                                System.out.println("Test1 m1()");
                                }
                }


class InheritanceDemo
{
                public static void main(String as[])
                {
                                Test1 t1=new Test1();
                                t1.m1();
                                System.out.println("A = "+t1.a);
                                }
                }

4) Polymorphism:-  Polymorphism is a process of single form behaving differently in different situation or cases.
You can achieve polymorphism in two ways as follows:-
1)      Compile time polymorphism
2)      Run time polymorphism

1)      Compile time polymorphism:-
  •  you can achieve compile time polymorphism by implementing method overloading.
  •  When you are invoking over loading method, method invocation decided by the compiler at compile time base on the method parameter.
  •  Compile time polymorphism is also called as static polymorphism.
Method Overloading:-
When you are writing multiple method within the same class with same name is call as method overloading.
you have to follow some rule:-
Rule:-
1)      Method name must be same.
2)      Return type can be any thing.
3)      No of parameter, type of parameter, order of parameter must be different.
Example:-
class CompileTimePolymorphism
{
                public void m1()
                {
                    System.out.println("with arguments");
                 }
                public void m1(int a)
                {
                     System.out.println("one argument a = "+a);
                    }
                public void m1(int a,int b)
                {
                    System.out.println("Two arguments a="+a+" b="+b);
                   }
                public void m1(String s1,int a)
                {
                    System.out.println("String s1="+s1+" a="+a);
                  }
public static void main(String as[])
{
        CompileTimePolymorphism p1=new CompileTimePolymorphism();
                                p1.m1();
                                p1.m1(10);                                         
                                p1.m1(20,30);
                                p1.m1("Chirag",30);
                                }
                }
2)      Run time polymorphism:-
  •  You can achieve run time polymorphism by using method overriding.
  • When  you invoking overriding method with super class reference variable which contain sub class object then method invocation will be decide at runtime based on object available
  • Runtime polymorphism also calls as dynamic polymorphism.
Note:- super class reference variable contain sub class object is call as dynamic dispatches .
Example:-
class Test
{
                public void m1()
                {
                                System.out.println("Test class m1()");
                                }
                public void m2()
                {
                                System.out.println("Test class m2()");
                                }
                }


class Test1 extends Test
{
                public void m1()
                {
                                System.out.println("Test1 class m1()");
                                }
                private void m2() /* You can't take private modifyer */
                {
                                System.out.println("Test1 class m2()");
                                }             
                }

class RunTimePolymorphism
{
                public static void main(String as[])
                {
                                Test t1=new Test1();
                                t1.m1();
                                }
                }                             
Note:- sub class method excess modifier must be same or higher than super class method excess modifier.
In this example it will give error by saying attempting to assign weaker access privileges; was public.

Java Collections:

Going for an Job Interview? be prepared with Java Collections framework. Java Collection framework is the most preferred topic by interviewers. It gives them the idea of how much effort the interviewee as taken to understand this framework and clear the interview.
Java Collection internally uses the primitive and core elements like Arrays etc. So if you are asked a question to explain the internal working of any of the Collection classes, don't be surprised. Be it an interview for an Junior Java developer or even for an Architect, Java Collection is always something that you will have on you plate.

Java provides many collection classes that can be used to store data. Knowing which collection class to use for best performance and optimum result is the key. In this section we will see how these different collection classes work internally.
ArrayList
ArrayList works on the principle of creating a array and adding elements to it.
ArrayList class has a member variable elementData which is a Object array;
Object[] elementData;
When we do List l = new ArrayList(); the array elementData is initalized with a size of 10

add(E element)
When a new element is added the capacity of the array elementData is checked and if it is completely filled that is all element 10 are filled a new array is created with a new capacity by using Arrays.copyOf. If the elementData array is not exhausted the new element is added in the array.
So adding a element in a array may take more time as a completely new array needs to be created with greater capacity and the data in the old array is transferred into the new array.

add(index i, E element)
On adding a element at a particular index in ArrayList, ArrayList checks if a element is already present at that index. If no than the element passed in add() is added at that index, otherwise a new array is created with the index kept vacant and the remaining element shifted to right.
For Eg:
List<Integer> l = new ArrayList<Integer>();
l.add(1);
l.add(2);
l.add(1,3);
l.add(4);

for(int i:l){
     System.out.println(i);
}

Output 
1
3
2
4
Here above we are trying to add 3 and position 1, since position 1 already has value '2'. A new array is created with value at index 1 kept vacant and the remaining elements are shifted to right. Than the element 3 is added at index 1.

get(int index)
The element present at that index in that array is returned. This is very fast.

When to use ArrayList
When the requirment is fetch data frequently and adding data is one time activity.

When not to use ArrayList
When the list is updated frequently

To understand ArrayList in more detail follow link Custom Array List. Here a custom Arraylist is created with basic add and get operations
Linked List
Linked List is a Doubly Linked List as desribed here Double Link List
With the Node called as Entry class having structure as
 class Entry {
 E element;
 Entry next;
 Entry previous;
 }

 LinkedList class also has a instance variable of type 'Entry' called 'header'. This is the 'start' element or node of the list.

add(E element )
 Every Time we call add(var);  a new instance of 'Entry' class is created and attached at the end of the list.

add(var,positon)
Inserts the specified element at the specified position in this list.
Shifts the element currently at that position (if any) and any subsequent elements to the right.

get(int index)
It iterates through the list and returns the element. This is very expensive and time consuming as opposed toArraList.get(int index)

When to use LinkedList
When the elements are getting added and removed frequently.

When not to use LinkedList
When you want to access or fetch a element by index.

HashMap
HashMap works on the principal of hashing. It stores values in the form of key,value pair and to access a value you need to provide the key.
For efficient use of HashMap the 'key' element should implement equals() and hashcode() method. equals() method define that two objects are meaningfully equal. hashcode() helps HashMap to arrange elements separately in a bucket. So elements with same hascode are kept in the same bucket together.
So when we want to fetch a element using get(K key), HashMap first identifies the bucket in which all elements of the same hascode as the hashcode of the 'key' passed are present. Than it uses the equals() method to identify the actual object present in the bucket.

Lets see how HashMap implements this logic internally.
Description: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdVvsTCicWAiczJNjeGCZM6b190Ph1hxhCJLp5wkcfA-7s-JIVZ514i21Qr3xGH5aAsnuTjhauNACozgF1Q3Nd_GCAbkZ9PQlBM25znQjqT8MXEs5_M1iiyoCl0gv17bZjt6mKVXlepq4_/s1600/HashMap.JPGFor fast access to a value HashMap places a element (both key and value) in aSinglyLinkedList(Bucket). All the elements that have the same hascode are placed in the same SinglyLinkedList. The number of SinglyLinkedList(buckets) depends upon how many objects are present with different hashcode. To hold these buckets together a array is used. The size of the array is initially defined to 12. And it changes as new elements with different hascodes are added. Lets see the pictorial view.
The structure of the 'Entry' class used above.
class Entry {
   K key;
   V value;
   Entry next;
   int hash;
}

HashMap also has some more variables which define the initial size of the array.

DEFAULT_LOAD_FACTOR = 0.75f;
DEFAULT_INITIAL_CAPACITY = 16;

Entry[] table = new Entry[DEFAULT_INITIAL_CAPACITY];

Hashset
Hashset is a special case
HashSet internally uses HashMap. Yes thats true.
HashSet has a instance variable called 'map' which is a instance of HashMap.

add(E element)
When we add a value in Hashset, Hashset internally adds a value in 'map' by calling put(E,o);
where E that is the key is the element passed in add(E element) of HashSet and 'o' as the value which is a dummy Object creted by doing Object o = new Object; which is common for all key's entered in HashMap 'map'.
HashMap internally checks wether the Key that is 'element' is already present by calling the equals method of 'element'.
This method returns false if the Key is already present in HashMap.

TreeMap
TreeMap is a structure which is designed to work as a Red - Black - Tree. Here each node has only two child nodes and the insertion is a tree happens same as the insertion strategy of Binary Search Tree explained here. So the elements in a TreeMap are always sorted.
The elements added is a TreeMap should implement comparable and provide implementation of compareTo method. On the basis of this TreeMap decides wether the node is smaller or greater than other node. If Comparable is not implemented, a class which is Comparator should be passed in the constructor of TreeMap. If both Comaparable and Comparator are present TreeMap uses Comparator implementation.

TreeMap internally mantains a List of Nodes with each node being a Entry<K,V> class which is actually a implementation of Map.Entry<K,V> interface.
The basic structure of this Entry class is 

class Entry{
 K key;
 V value;
 Entry left = null;
 Entry right = null;
 Entry parent;
 boolean color = BLACK;
}


Entry<K,V> of TreeMap has inetrnally three entries of Entry<K,V> class : left,right,parent;
When we use put(K,V) method it checks if root is pointing anywhere if no it makes the instance of Entry<K,V> and point to root;
The constructor of Entry<K,V> takes key, value and parent. In this case parent is null;
For the next time we enter something using put(K,V) it first identifies the comparison machenism to use. First it check the Comparator class is present or not . This class is passed when creating the instance of TreeMap. If not present it uses the Key's Comparable implementation.
It then traverse through root and compares each node with the node entered and depending upon the comparison places the node either left or right of the parent node.


J2SE 5 Features
The important features of J2SE 5 are generics and assertions. Others are auto-boxing, enum, var-args, static import, for-each loop (enhanced for loop etc.


JavaSE 6 Features

The important feature of JavaSE 6 is premain method (also known as instrumentation).
  • Instrumentation (premain method) (Java 6)

JavaSE 7 Features

The important features of JavaSE 7 are try with resource, catching multiple exceptions etc.
  • String in switch statement (Java 7)
  • Binary Literals (Java 7)
  • The try-with-resources (Java 7)
  • Caching Multiple Exceptions by single catch (Java 7)
  • Underscores in Numeric Literals (Java 7)

For-each loop (Advanced or Enhanced For loop):

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.

Advantage of for-each loop:

  • It makes the code more readable.
  • It elimnates the possibility of programming errors.
Syntax : 

for(data_type variable : array | collection){}

Example : 

  1. class ForEachExample1{  
  2.   public static void main(String args[]){  
  3.    int arr[]={12,13,14,44};  
  4.   
  5.    for(int i:arr){  
  6.      System.out.println(i);  
  7.    }  
  8.   
  9.  }   
  10. }  
  


1 comment:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Agile coach during this lockdown period everyone can use it wisely.
    Agile coach certification Bangalore

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...