top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

how to prevent a client from directly instantiating your concrete classes?

+1 vote
1,508 views

How would you prevent a client from directly instantiating your concrete classes?

posted Oct 11, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Try something like this

public class Record {
    private static final int MAX_INSTANCES = 1;
    private static volatile int instanceCounter = 0;

    private Record() {
        if (instanceCounter >= MAX_INSTANCES)
            throw new RuntimeException("max instances exceeded");

        instanceCounter ++;
    }
}

In the above example you can instantiate max 1 time, change the value of MAX_INSTANCES accordingly as per need.

I hope I understood your question correctly.

answer Oct 11, 2016 by Salil Agrawal
Similar Questions
+1 vote

Why we need transient keyword to prevent serialization of a particular data member. we can also make it static because static data member can not be serialized.

+2 votes

What is the difference between abstract class and concrete class in java. If concrete class is final then how can inherit concrete class, can someone please explain in detail?

...