Wednesday, 6 April 2016

How many ways create an Object In Java?

Ques : How many ways create an Object In Java?

In interview asked how to create an object in java generally and everyone says
using the “new” operator to create an Object of a Class. But is it the only way to create an Object?


Simple answers is NO, then in how many ways we can create Object of a Class. 

There are four different ways to create objects in java:
  • Using New keyword
  • Class.forName()
  • Using Clone()
  • Using Deserilization

1. Using new keyword:

This is the most common way to create an object in java. Almost 99% of objects are created in this way.



MyObject object = new Object();

2. Using Class.forName():

If we know the name of the class & if it has a public default constructor we can create an object in this way.

 


MyObject obj = (MyObject) class.forName("object").newInstance();



3. Using clone():

The clone() can be used to create a copy of an existing object.

             
  MyObject obj new MyObject();

  MyObject object = (MyObject )obj.clone();

4. Using Object Deserialization :

Object deserialization is nothing but creating an object from its serialized form.




ObjectInputStream istream = new objectInputStream(some data);
MyObject object=(MyObject) instream.readObject();

Tuesday, 5 April 2016

Inheritance :


Inheritance is one such concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes.

In Java, there are two classes:
  • Parent class ( Super or Base class)
  • Child class (Subclass or Derived class )
A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.

Inheritance defines IS-A relationship between a Super class and its Sub class. extends and implements keywords are used to describe inheritance in Java.


Inheritance is further classified into 4 types:
  • Single Inheritance 
  • Multilevel Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance
Note : Multiple inheritance is not supported in java

1.Single Inheritance :




2.Multilevel Inheritance:



3.Multiple Inheritance : 

Having more than one Parent class at the same level is called multiple inheritance.

  • Any class can extends only one class at a time and can’t extends more than one class simultaneously hence java won’t provide support for multiple inheritance.
  • But an interface can extends any number of interfaces at a time hence java provides multiple inheritance support through interfaces.

4.Hierarchical Inheritance :



5.Hybrid Inheritance : 



No of Occurrence in Array

package com.tutorial4u; import java.util.HashMap; /************************************************************  No of Occurrence in Array...