Oracle Interview Question
SDE-2sCountry: India
Interview Type: Phone Interview
There isn't a reasonable way to find out whether or not an instance of a particular class already exists.
If you need to know this information, create a static boolean field and set it from the constructor:
class MyClass {
private static bool instanceExists = false;
public MyClass() {
MyClass.instanceExists = true;
}
}
A Static integer member , incremented each time a constructor is called ?
public class MyClass {
private static int count = 0;
public MyClass() {
count++ ;
}
int getCount()
{
return count;
}
public static void main(String [ ] args)
{
System.out.println("TEST") ;
MyClass j1 = new MyClass() ;
MyClass j2 = new MyClass() ;
MyClass j3 = new MyClass() ;
System.out.println("COunt == " + j3.getCount()) ;
}
}
package com.java.basic;
class A {
private static int _INSTANCE_COUNT = 0;
public A() {
_INSTANCE_COUNT++;
}
@Override
public void finalize() {
--_INSTANCE_COUNT;
}
public static boolean isCreated() {
return (_INSTANCE_COUNT > 0);
}
}
public class B {
public static boolean isACreated() {
return A.isCreated();
}
public static void main(String[] args) {
A a = new A();
System.out.println(isACreated());
}
}
package com.java.basic;
class A {
private static int _INSTANCE_COUNT = 0;
public A() {
_INSTANCE_COUNT++;
}
@Override
public void finalize() {
--_INSTANCE_COUNT;
}
public static boolean isCreated() {
return (_INSTANCE_COUNT > 0);
}
}
public class B {
public static boolean isACreated() {
return A.isCreated();
}
public static void main(String[] args) {
A a = new A();
System.out.println(isACreated());
}
}
I can think off couple of approaches:
1. Use a static variable in class A to keep counter of the instances created and read it before creating The instance of B.
2. Use Mediator pattern where A sends a communication to the mediator when it's instance is created. B checks with the mediator if the instance of A is created. Otherwise, the mediator can notify B of the A's instance creation.
This concept can be extended to use queues/topics as in messaging (JMS).
class A {
}
class B {
private boolean isInstanceOf;
B(Object a) {
if(a instanceof A) {
this.isInstanceOf = true;
} else {
this.isInstanceOf = false;
}
}
public boolean getIfInstanceOf() {
return isInstanceOf;
}
}
class CheckInstance {
public static void main(String[] args) {
A a = new A();
B b = new B(a);
B b1 = new B(b);
System.out.println(b.getIfInstanceOf());
System.out.println(b1.getIfInstanceOf());
}
}
1. Set some B's variable in A's constructor. For this we need to be sure that instance of B is already created before creating instance of A.
This is kind of sharing a variable within classes. More generic implementation will be like Observer pattern.
This is very simple and basic implementation.
- ash.taunk3 June 02, 2015