Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Java in General
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Tim Cooke
Campbell Ritchie
paul wheaton
Ron McLeod
Devaka Cooray
Sheriffs:
Jeanne Boyarsky
Liutauras Vilda
Paul Clapham
Saloon Keepers:
Tim Holloway
Carey Brown
Piet Souris
Bartenders:
Forum:
Java in General
Limiting creation of an object by a single class
Gaurav Gupta
Greenhorn
Posts: 13
posted 21 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Hi,
I have a class A and a class B.
Now - can I do an enforcement which says that only B (and no other class) should be able to create objects of class A?
thanks,
Gaurav
Ben Dover
Ranch Hand
Posts: 91
posted 21 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Your problem is very similar to the singleton
pattern
, except for a nested class. Try this:
class B { static A getA() { return new A(); } // private nested class static class A { private A() { // constructor can only be called by A or B } public void hello() { System.out.println("hello from new A"); } } } class Test { public static void main(String[] args) { B.A a; // a = new A() would be illegal because // A's constructor is priv. a = B.getA(); a.hello(); } }
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
interesting question
Doubt about diagram class (realization)
In the static innrer classes
Concrete class
Representation in UML vs Java
More...