What significance of protected Constructors?

Showing Answers 1 - 9 of 9 Answers

Pratiksha Powar

  • Dec 29th, 2005
 

Has anyone observed how task manager works?

Well, when u start the task manager , it'll open in a window. However many times you try to start it, it will return the same instance. this where you require a private constructor. So that if there is a class called TaskManager you should not be able to generate a object of it any number of times you want.

This class will have a static method which can be called without any object. The static method will check whether an instance of Task Manager already exists or not. if exists it will return the same pointer and if doesn't only then it will call the private constructor. Such a class is called a Singleton class.

Now if you want to inherit that class, you need the base class constructor to be exposed. In this case we use a protected constructor.

  Was this answer useful?  Yes

Harsha jayaramachar

  • Mar 20th, 2006
 

Consider Class A extends Class B. If Class B has protected constructors then

1.Cannot create object from Class A directly.

2.Indirectly you can create object of Class A by instantialting Class B.

ching wu

  • Apr 20th, 2006
 

I think you can still create an object of the class even if the construtor is "protected". But you can do so only in the same package. You can also extend the class in the same package.

But if the constructor is "private" then you cant extend the class. If you want to create an object of that class use static method.

  Was this answer useful?  Yes

what if I have a scenario?


public class A{

protected A(String str){

//code block
}

public A(){
this("name1");

}

public static void main(){
new A();

//now you can use the protected constructor..
//or you can also use the static block to call the protected constructor..cant u?
}
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions