• Post Reply Bookmark Topic Watch Topic
  • New Topic

Private constructor  RSS feed

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I instantiate a class with private construtor in the main() in same class ?
This code i staken rom mocktest.
Can I instantiate StrEq as shown in main() ? or do I need to access private constructor with public static method ?
I was under the impression that when there is a private constructor or member in a class, I can not access it in the main() of the same class directly. I have to access it through a public method of the same class. but it looks like my understanding is not correct, we can access a private member of a class in the main() direwstly. Please correct , if I am wrong. Please also explain, why is private constructor is being initialized in main(), if we have to use static public method to acces it.

Thanks
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I instantiate StrEq as shown in main() ?
Yes.
or do I need to access private constructor with public static method ?
main() is a public static method.
I was under the impression that when there is a private constructor or member in a class, I can not access it in the main() of the same class directly.
Incorrect. Where did you get that impression? The definition of private (method or constructor) is that you can only access it from within the class. The main() method is in the class. main() is only special because the JVM knows to call it when starting the application.
 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
BTW, Your code is much more readable when indented properly. I also added a private run() method that is called from main()

And you have a bug on line 13. Do you see it? (unless you want "Marcus" to be not equal to "Marcus")
 
Campbell Ritchie
Marshal
Posts: 56541
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suspect the idea was to show that in that instance, s1 != s2.

Don't put all that executable code into the constructor; constructors are intended for setting up the object in a consistent state. Put the code which prints the message in a method, and have s1 and s2 as private fields of the class.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!