Reputation: 42032
in other words, can someone explain to me the purpose of this:
Consumer(Producer p) {
producer = p;
}
in the context of:
class Consumer extends Thread {
Producer producer;
Consumer(Producer p) {
producer = p;
}
}
as I understand, it appears to be a method with no signature, or a constructor since it shares the class name, yet it doesn't show up in my IDE as such. Can someone explain what it is and what it does?
Any help would be hugely appreciated.
Upvotes: 1
Views: 653
Reputation: 14918
As already mentioned, that is a package protected constructor, i.e. it can only be called from methods of the class itself or other classes in the same package. I'm not sure what benefit that has over the more commonly used protected
or private
constructors, which prevent a class from being directly instantiated and are commonly used to implement the Singleton pattern.
Upvotes: 0
Reputation: 120316
Consumer(Producer p) { ... }
is a constructor for the Consumer
class.
You typically see constructors as public
, e.g.:
public Consumer(Producer p) { ... }
However, when the public
(or any access modifier, e.g. protected
, or private
) is not specified (for any method or member, including constructors), the constructor is only available to the package the class is declared in.
Have a look at Oracle's tutorial on access control.
Upvotes: 3
Reputation: 346327
Yes, that's a constructor. It may look like a "method with no signature" syntactically (more specifically, a constructor cannot have a return type, but may have access modifiers and of course parameters), but it's really quite different from a method in several ways.
The purpose of a constructor is to create instances (objects) of the class. With some relatively exotic exceptions (cloning and deserialization), every Java object is created by calling a constructor. Every class has at least one constructor, but if none is declared an the superclass has a constructor with no parameters, the compiler implicitly adds a parameterless constructor that does nothing except call the superclass constuctor. Similarly, the first thing any constructor does is call a superclass constructor. Again, this can be implicit if there is a parameterless constructor in the superclass.
As for why constructors don't show up in your ide: it's probably a configuration option. To say more, we'd have to know which IDE that is.
Upvotes: 1
Reputation: 5425
You are looking at a constructor of class Consumer. The only problem I can see is it is not given a access level (public, private, etc...), so it looks like it will default to package-protected, meaning only classes within the same package can see it.
Upvotes: 4