• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java constructore

 
Adi Sharma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I got the following and could not make any sense out of it :

"Constructors can use any access modifier, including private. (A private
constructor means only code within the class itself can instantiate an object
of that type, so if the private constructor class wants to allow an instance
of the class to be used, the class must provide a static method or variable that
allows access to an instance created from within the class.)"

Can anyone help me out with this.

Thank You
Aditya Sharma
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you try this code



So basically no class other than Packed itself can create its object. So if you want other classes to have objects of Packed class, you must declare a static method in Packed which will return objects of Packed

 
Adi Sharma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot
 
Adi Sharma
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried doing this :

class class5
{
private class5(){} //private constructors

public static class5 getInstance()
{
return new class5();
}
}

class class6 extends class5
{
public static void main(String [] args)
{
class5 c= class5.getInstance();
}

}

But the compiler shows an error with class6 :
Implicit super constructor class5() is not visible for default constructor. Must define an explicit constructor

what does this means. even though I made a static method that handles the new objects.

Any insight ???

thanks
Aditya Sharma
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This line is creating the problem. A class with only private constructor(s) cannot be subclassed neither instantiated outside the class itself...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic