0

does the constructor need a access modifier

- A constructor name must be same as its class name. - A constructor must have no explicit return type. public class Vehicle { private String color; Vehicle() { color = "Red"; } } as seen above is says that constructor requires same name as class and its return type should not be given. it doesnt say anything about access modifier. although it is not given in the class" does method vehicle needs to be defined as public or private"

5th Feb 2017, 3:50 PM
clins
3 odpowiedzi
+ 1
Without an explicit access modifier the constructor (and methods in general) gets the default "package private visibility", meaning only visible for the class itself, and classes in the same package. Declaring a constructor as public makes it visible for all classes everywhere, while private makes sure that no other class could instantiate objects from that class. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
5th Feb 2017, 4:08 PM
Kristoffer Andersson
Kristoffer Andersson - avatar
0
sorry my bad....as i progressed to next classes i understood that it can be given. but what is the difference between constructors with access modifiers and without it.does it matter if it does not mention its access modifier
5th Feb 2017, 3:56 PM
clins
0
Of course it matters. For example if you don't want any other class to derive from your class, you make the constructor modifier private.
5th Feb 2017, 4:54 PM
Jannick