Reputation: 6393
I thought I understood pretty much all there was to know about Java's access modifiers until one of my teammates just committed some code with something I've never seen before.
Take a look at the following code while paying attention to the only two access modifiers,
public class Type {
private
int typeID;
String name;
String description;
public
void setTypeId(int arg)
{
typeID=arg;
}
int getTypeId()
{
return typeID;
}
void setName(String arg)
{
name=arg;
}
String getName()
{
return description;
}
void setDescription(String arg)
{
description=arg;
}
String getDescription()
{
return description;
}
}
My teammate is new to Java but comes from a C++ background which is why I think he set up the private
and public
access modifiers like that (That's how they're done in header files for C++). But is this valid in Java. I have never seen this syntax before in Java and I cannot find any documentation on it online.
If this is valid does it mean typeID
, name
, and description
are all private and that all the functions under public
are in fact public. Or does it mean that only typeID
is private and setTypeID
is private (since they're the two member declarations under the two access modifiers.
Upvotes: 0
Views: 508
Reputation: 17
The typId attribute was defined as private, setTypeId was defined as public, and others attributes and methods are as default visible only for members of same package (package private).
In java each instruction end with ';' terminator;
What is more like what you think is this:
public String name, description;
For instruction above the two attributes are affected by 'public' modifier.
:)
Upvotes: 0
Reputation: 280168
The lack of access modifier indicates package private.
The single private
modifier applies to the typeID
field. The single public
modifier applies to the setTypeId
method.
Whitespace and indentation is meaningless in Java. (It doesn't matter in C++ either afaik, but in C++ you'd have private:
, not just private
.)
Put differently, this
public class Type {
private
int typeID;
String name;
String description;
is the same as
public class Type {
private int typeID;
String name;
String description;
which is the same as
public class Type { private int typeID; String name; String description; //...
Upvotes: 4