Java Object Creation & Destruction - object

I've just now started learning Java and so far completed Class, Objects and Variables.
Here is my program,
class MyClass{
int x = 10;
psvm(String[] args){
MyClass mcl1 = new MyClass(); //1st object;
MyClass mcl2 = new MyClass(); //2nd object;}
}
My Question,
-> Will the first object created out of the same class get destroyed once the second object is created?

AFAIK there's literally no limit to how many new and unique objects you can create.

No the first will be not destroyed.
You can create a thousand instances of MyClass class.
Good continious learning.

Related

Is it possible to implement Singleton Pattern in multithread program?

There is a Windows.Forms.Timer in my project. In the Timer.Tick Method Handler I create an instance of Manager class (My Own Class) And In Manager Constructor I create some threads and store them in a dictionary. The dictionary located in a class named TransManager which implemented with singleton pattern.
public class TransManager {
private static volatile TransManager _Instance;
public static TransManager Instance
{
get
{
lock (syncRoot)
{
if (_Instance == null)
_Instance = new TransManager();
}
return _Instance;
}
}
}
I implemented the class TransManager because I need to have all created threads which produced from different instance of Manager class in same place.
The problem is when a new instance of Manager adds threads in the dictionary the last threads are gone!
Note: When I create All threads within an instance of Manager class then all thread can share the dictionary safe. According to this can I say it is possible to singleton across threads?
I checked; There is no Dictionary.Clear() in my code!
I hope the problem was clear! Ask me if it is not.
Thank you.

Code restricting: Create of more than one object in private constructor in C#

I want to create a code in C# for Private constructor.
I want that it should allow only one object to be created but when I try to create more than one a message showing no more object can be created should be shown.
I don't want to use static constructor in this code.
How do I do that in C#?
You may use static counter or flag that will be set in your private counstructor to show that at least one instance were created.
But first of all, I suggest you to pay attention to Singleton pattern.
Simple, this is the classic singleton pattern:
public class MyClass
{
public static MyClass Instance;
private MyClass()
{
if (Instance != null)
throw new InvalidOperationException("no more object can be created");
// do other constructor logic
Instance = this;
}
}
Please note that synchronization has been left out. This code need synchronization for thread safe purpose.

Adding to a dictionary c#

I have a dictionary that contains classes. However, I have a lot of classes to add to the dictionary and I would like to eliminate the long list of adds, because it's starting to look messy. I was thinking of having all the data in a file and loading it to add to the dictionary, but then I realized that every time I wanted to create and add a new class, I would have to modify the file. I would prefer to have to include something in my newly created class that would automatically add it to the dictionary. I'm not even sure this is possible, so I would appreciate any help.
Try to use reflection to dynamically locate all the required classes. Create an instance of Assembly where your classes are defined and try to filter them out. An example below shows how to locate all the classes whose name ends with Task.
var assembly = Assembly.GetExecutingAssembly();
var taskTypes = assembly.GetTypes()
.Where(t => t.Name.EndsWith("Task") && t.IsClass);
Dictionary<string, object> instances =
new Dictionary<string, object>(taskTypes.Count());
foreach (Type classType in taskTypes)
{
object instance = Activator.CreateInstance(classType);
instances.Add(classType.Name, instance);
Console.WriteLine("Registered key {0} with object of type {1})",
classType.Name,
instance);
}
I've used Activator.CreateInstance method to create instances of your classes, but this might not be possible in your case depending on whether they have parameterless contructors etc.
Another option might be to use one of the available IoC containers like autofac but I need more details on your problem before I can give a proper advice on this.
Make the dictionary a static field of some class, or make the "add class to dictionary" a static method.
Then, you can use a static constructor to add each class to the dictionary:
class ClassDict {
...
public static void AddClass(Type t) {
...
}
}
class Foo {
static Foo() {
ClassDict.AddClass(typeof(Foo));
}
}

Constructor and object intitiation

When we access "this \ Me" in the constructor of any class, how is it that "this" is already available while its yet getting constructed? Has a temporary creation of the instance already happened before the constructor call? If so then does this mean these Constructors are called after the actual object initialisation?
the object is created and the memory is allocated before you initialize it with the constructor....
ex
1. you create the object;
MyObject myObject;
2. you initialize it
myObject = new MyObject();
these 2 steps are also done when you are doing this:
MyObject myObject = new MyObject();
Edit:
in the constructor this goes for myObject
In C++, when you have
Foo::Foo(int x)
: frob(x) {
this->frob = x;
}
then the construction really happens exactly between then : and the first brace:
:<here>{
In the the body of that constructor, the object is fully constructed, therefore, using this there is well defined.

Groovy adding code to a constructor

Is there a way in Groovy that I can add code to a constructor when a class is instantiated? I have a Groovy class (but I can't modify the source of this particular one), but I was hoping there was a way to inject code (maybe via the metaclass) so my code gets run as part of the constructor (in this case there is only one, default constructor).
Thanks,
Jeff
You can override the constructor, but it's a little tricky, particularly if you're overriding the default constructor. You need to assign a closure to the class's metaClass.constructor, and the closure should return a new instance. The tricky part is that if you call the constructor you've overriden, you'll get into a recursive loop and generate a stack overflow. You need another way to get an instance of the class, such as a different constructor.
For testing, it's sometimes possible to get around this limitation. Usually, it's enough to first instantiate an object, then override the constructor to return the existing instance. Example:
class MyObject {
String something
MyObject() { something = "initialized" }
}
testInstance = new MyObject()
testInstance.something = "overriden"
MyObject.metaClass.constructor = { -> testInstance }
aNewObject = new MyObject()
assert aNewObject.is(testInstance)
assert aNewObject.something == "overriden"
It is possible to add new constructors or replace the old one. If you need the original constructor, you can use reflection for that:
MyObject.metaClass.constructor = { -> // for the no-arg ctor
// use reflection to get the original constructor
def constructor = MyObject.class.getConstructor()
// create the new instance
def instance = constructor.newInstance()
// ... do some further stuff with the instance ...
println "Created ${instance}"
instance
}
Note that you have to change this if you have parameters to your constructors, e.g:
// Note that the closure contains the signature of the constructor
MyObject.metaClass.constructor = { int year, String reason ->
def constructor = MyObject.class.getConstructor(Integer.TYPE, String.class)
def instance = constructor.newInstance(
2014, "Boy, am I really answering a question three years old?")
// ... do some further stuff with the instance ...
println "Created ${instance}"
instance
}
PS: Note that when you want to add constructors which are not yet existent, use the << operator instead: MyObject.metaClass.constructor << { /* as above */ }.
You can bypass the limitations in the solution proposed by storing the original constructor using standard Java reflection. For example, this is what I do initialize a class (basic injection) in a spock test:
def setupSpec() {
MockPlexusContainer mockPlexusContainer = new MockPlexusContainer()
def oldConstructor = MY_CLASS.constructors[0]
MY_CLASS.metaClass.constructor = { ->
def mojo = oldConstructor.newInstance()
mockPlexusContainer.initializeContext(mojo)
return mojo
}
}
This gets invoked only once, but eveytime someone calls a constructor I get a different instance avoiding cleaning values and ensuring thread safety.

Resources