Java Interview Questions
Different ways to create an Object in java?
1) using new
Netflix netflix = new Netflix();
2) using class.forName()
Netflix netflix =Class.forName("com.bellinfo.Netflix").newInstance();
3) by clone()
Netflix netflix1 = new Netflix();
Netflix netflix2 = (Netflix) netflix1.clone();
4) by desearlization (the object which is already Seralized)
ObjectInputStream ooi = new ObjectInputStream(anInputStream);
Netflix netflix = (Netflix) ooi.readObject();
Can we create an instance for a private constructor class out-side of the same class?
Yes,
class Netflix { private Netflix(){} } public static void main(String args[]){ try { Class c = Class.forName("com.bellinfo.corejava.Netflix"); Constructor con[] = c.getDeclaredConstructors(); con[0].setAccessible(true); con[0].newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
Difference between instance vs object ?
A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance. An 'instance' is a variable in memory that only has a memory address of an object in it.
Difference between association vs aggregation vs composition ?
is a vs has a relationship in java ?